Python随笔(三)、python基础

2023-01-31 04:01:49 python 基础 随笔

一、练习:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: dictionary.py
@time: 2017/11/19
"""
'''
有如下集合[11,22,33,44,55,66,77,88,99,110,121,132,143,154,165,176,187],将所有大于66的值保存在字典的第一个key中,将小于66的值保存在第二个key的值中
即:{'k1':大于66,'k2':小于66}
'''
######方法一
#dic = {}
#all_list = [11,22,33,44,55,66,77,88,99,110,121,132,143,154,165,176,187]
#for i in all_list:
#    if i > 66:
#        if "k1" in dic.keys():
#            dic["k1"].append(i)
#        else:
#            dic['k1'] = [i,]
#    else:
#        if "k2" in dic.keys():
#            dic["k2"].append(i)
#        else:
#            dic['k2'] = [i,]
#print(dic['k1'])
#print(dic['k2'])

#方法二、
all_list = [11,22,33,44,55,66,77,88,99,110,121,132,143,154,165,176,187]
dic = {'k1':[],'k2':[]}
for item in all_list:
   if item>66:
       dic["k1"].append(item)
   else:
       dic["k2"].append(item)
print(dic['k1'])
print(dic['k2'])

set集合:

#!usr/bin/env Python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: set.py
@time: 2017/11/20
"""
#爬虫
s1 = set()
s1.add("alex")
print(s1)
s1.add('alex')
print(s1)

返回结果:

{'alex'}

{'alex'}

#访问速度快

#天生解决了重复问题


clear

copy


过滤重复功能:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: set.py
@time: 2017/11/20
"""
#爬虫
s2 = set(["alex","eric","tony","alex"])
print(s2)

返回结果:

{'eric', 'alex', 'tony'}


difference

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: set.py
@time: 2017/11/20
"""
#爬虫
s2 = set(["alex","eric","tony","alex"])
print(s2)

s3 = s2.difference(["alex","eric"])
print(s3)

返回结果:

{'tony', 'eric', 'alex'}

{'tony'}

difference

difference_update

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: set.py
@time: 2017/11/20
"""
#爬虫
#去除重复的集合
s2 = set(["alex","eric","tony","alex"])
print(s2)
#与s2不相同的部分
s3 = s2.difference(["alex","eric"])
print(s3)
#删除当前set中的所有包含在参数集合里的
s4 = s2.difference_update(["alex","eric"])
print(s4)

返回结果:

{'tony', 'eric', 'alex'}

{'tony'}

None


intersection    取交集

isdisjoint         如果没有交集返回true

issubset           是否是子集

issuperset        是否是父集

pop                  移除

remove             移除

symmetric_difference_update   差集

uNIOn                并集

update              更新


# 数据库中原有
old_dict = {
    "#1":{ 'hostname':c1, 'cpu_count'2'mem_capicity'80 },
    "#2":{ 'hostname':c1, 'cpu_count'2'mem_capicity'80 }
    "#3":{ 'hostname':c1, 'cpu_count'2'mem_capicity'80 }
}

  

# cmdb 新汇报的数据
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count'2'mem_capicity'800 },
    "#3":{ 'hostname':c1, 'cpu_count'2'mem_capicity'80 }
    "#4":{ 'hostname':c2, 'cpu_count'2'mem_capicity'80 }

}

交集:要更新的数据

差集:原来,要更新

1、原来没有  --》 新加入

2、原来有      --》 更新

3、新无,原来有  --》原来删除


三个列表:

    要更新的数据

    要删除

    要添加


#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: set.py
@time: 2017/11/20
"""


# 数据库中原有
old_dict = {
   "#1":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 },
   "#2":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 },
   "#3":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 },
}

# cmdb 新汇报的数据
new_dict = {
   "#1":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 800 },
   "#3":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 },
   "#4":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 80 },
}
old = set(old_dict.keys())
new = set(new_dict.keys())
#更新的集合
update_set = old.intersection(new)
#删除的集合
delete_set = old.symmetric_difference(new)
#添加的集合
add_set = new.symmetric_difference(update_set)
print(update_set)
print(delete_set)
print(add_set)
print(old)
print(new)

返回结果:

{'#1', '#3'}

{'#2', '#4'}

None

{'#1', '#2', '#3'}

{'#4'}

例子:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: s1.py
@time: 2017/11/20
"""
s1 = set([11,22,33])
s2 = set([22,44])
ret1 = s1.difference(s2)
ret2 = s1.symmetric_difference(s2)
print(ret1)
print(ret2)

返回结果:

{33, 11}

{33, 11, 44}


collections系列

Http://www.cnblogs.com/wupeiqi/articles/5115190.html

1.png

collections   计数器     

most_common      最多的次数

element                 所有的元素

2.png

3.png

4.png

orderedDict   有序字典

1.png

pop

popitem

setdefault     设置默认值

update         更新原来的数据

1.png

默认字典:

2.png

可命名元祖:创建类

2.png

双向队列(deque)

https://www.cnblogs.com/zhenwei66/p/6598996.html

单向队列(queue),需要导入queue模块

https://www.cnblogs.com/zhenwei66/p/6599136.html


邮件模块:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: mail.py
@time: 2017/12/19
"""
import smtplib
from email.mime.text import MIMEText
from email.utils import fORMataddr
def mail():
   ret = True
   try:
       msg = MIMEText('how are you,you are a Good men','plain','utf-8')
       msg["From"] = formataddr(["陈继松",'chenjisong@wtoip.com'])
       msg["To"] = formataddr(["406564728@qq.com",'406564728@qq.com'])
       msg['Subject'] = "主题"

       server = smtplib.SMTP("smtp.wtoip.com",25)
       server.login("chenjisong@wtoip.com","**************")
       server.sendmail('chenjisong@wtoip.com',["406564728@qq.com",], msg.as_string())
       server.quit()
       return ret
   except Exception:
       ret = False
       return ret

ret = mail()
if ret:
   print('发送成功')
else:
   print('发送失败')


默认参数:

def show(a1,a2=999,a3=333,a4=444,a5=555):
   print(a1,a2,a3,a4,a5)
show(111,222,333,444,555)


指定参数:

def show(a1,a2):
   print(a1,a2)
show(a2=33334,a1=555556)

动态参数,个数无限制
def show(**arg):
   print(arg,type(arg))
show(a1=123,a2=456,a3=789)
返回结果:
E:\python36\python.exe C:/Users/Administrator/PyCharmProjects/2017-12-10/2017-12-19/s4.py
{'a1': 123, 'a2': 456, 'a3': 789} <class 'dict'>

动态参数(强强联合):
def show(*args,**kwargs):
   print(args,type(args))
   print(kwargs,type(kwargs))
show(11,222,33,44,n1=88,alex="sb")
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
(11, 222, 33, 44) <class 'tuple'>
{'n1': 88, 'alex': 'sb'} <class 'dict'>

def show(*args,**kwargs):
   print(args,type(args))
   print(kwargs,type(kwargs))
l = [11,22,33,44]
d = {'n1':88,'alex':'sb'}
show(l,d)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
([11, 22, 33, 44], {'n1': 88, 'alex': 'sb'}) <class 'tuple'>
{} <class 'dict'>

如果我想把l放入列表里面,把d放入字典里面,则:
def show(*args,**kwargs):
   print(args,type(args))
   print(kwargs,type(kwargs))
l = [11,22,33,44]
d = {'n1':88,'alex':'sb'}
show(*l,**d)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
(11, 22, 33, 44) <class 'tuple'>
{'n1': 88, 'alex': 'sb'} <class 'dict'>

22 python s12 day3 使用动态参数实现字符串格式化
1、
alex = sb的三种方式:
s1 = "{name} is {acter}"
d = {'name':'alex','acter':'sb'}
#result = s1.format(name='alex',acter='sb')
result = s1.format(**d)
print(result)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
alex is sb

2、字符串格式化
s1 = "{name} is {acter}"
result = s1.format(name='alex',acter='sb')
print(result)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
alex is sb

3、
s1 = "{0} is {1}"
l = ['alex','sb']
result = s1.format('alex','sb')
result = s1.format(*l)
print(result)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
alex is sb

23 python s12 day3 Python lambda表达式
def func(a):
   a +=1
   return a
result = func(4)
print(result)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
5
lambda表达式,简单函数的表示方式:
func = lambda a: a+1
#创建形式参数a
#函数内容a+1,并把结果return
ret = func(99)
print(ret)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
100

24、内置函数:
#绝对值:
a = -100
b = a.__abs__()
print(b)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
100

更多详见:http://www.runoob.com/python/python-built-in-functions.html

map的巧用:
li = [11,22,33,44]
new_li = map(lambda x:x+100,li)
l = list(new_li)
print(l)
返回结果:
E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/2017-12-10/2017-12-19/s4.py
[111, 122, 133, 144]





相关文章