参考文献:http://www.cnblogs.com/wupeiqi/articles/4943406.html
set集合
集合的特点:
- 解决重复问题
- 访问速度快
集合的常用方法如下:
>>> s1 = set([11,22,33,44])>>> s1set([33, 11, 44, 22])>>> s1.add(66)>>> s1set([33, 66, 11, 44, 22])
1 >>> s1 = set([11,22,33,44])2 >>> s13 {33, 11, 44, 22}4 >>> s1.clear()5 >>> s16 set()
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([123,22,33,543])3 >>> s1.difference(s2)4 {11, 44}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([123,22,33,543])3 >>> s1.difference_update(s2)4 >>> s15 {11, 44}6 >>> s27 {33, 123, 22, 543}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([123,22,33,543])3 >>> s1.intersection(s2)4 {33, 22}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([123,22,33,543])3 >>> s1.intersection_update(s2)4 >>> s15 {33, 22}
1 >>> s1 = set([11,22,33,44])2 >>> s1.pop()3 334 >>> s15 {11, 44, 22}
1 >>> s1 = set([11,22,33,44])2 >>> s1.remove(11)3 >>> s14 {33, 44, 22}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([123,22,33,543])3 >>> s1.isdisjoint(s2)4 False5 >>> s1 = set([11,22])6 >>> s2 = set([33,44])7 >>> s1.isdisjoint(s2)8 True
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([11,22])3 >>> s2.issubset(s1)4 True5 >>> s1.issubset(s2)6 False
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([11,22])3 >>> s2.issuperset(s1)4 False5 >>> s1.issuperset(s2)6 True
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([11,22,55])3 >>> s1.symmetric_difference(s2)4 {33, 44, 55}5 >>> s2.symmetric_difference(s1)6 {33, 44, 55}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([11,22,55])3 >>> s1.symmetric_difference_update(s2)4 >>> s15 {33, 44, 55}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([11,22,55])3 >>> s1.union(s2)4 {33, 22, 55, 11, 44}
1 >>> s1 = set([11,22,33,44])2 >>> s2 = set([11,22,55])3 >>> s1.update(s2)4 >>> s15 {33, 22, 55, 11, 44}
#!/usr/bin/env python# -*- coding:utf-8 -*- old_dict = { '1':{ 'hostname':'c1','cpu':2,'mem':'123'}, '2':{ 'hostname':'c1','cpu':2,'mem':'123'}, '3':{ 'hostname':'c1','cpu':2,'mem':'123'}} new_dict = { '1':{ 'hostname':'c1','cpu':2,'mem':'1234'}, '3':{ 'hostname':'c1','cpu':2,'mem':'123'}, '4':{ 'hostname':'c2','cpu':2,'mem':'123'}} old_set = set(old_dict.keys())new_set = set(new_dict.keys()) update_set = old_set.intersection(new_set)#交集:需要更新的集合# delete_set = old_set.symmetric_difference(update_set)#差集:需要删除的集合# add_set = new_set.symmetric_difference(update_set)#差集:需要添加的集合 delete_set = old_set.difference(update_set) #与需要更新的集合对比,找出需要删除的数据add_set = new_set.difference(update_set) #与需要更新的集合对比,找出需要添加的数据for i in delete_set: old_dict.pop(i)for k in add_set: old_dict[k] = new_dict[k]for v in update_set: old_dict[v] = new_dict[v] print(old_dict)
collections常用方法
使用collections需要导入模块
import collections
1.Counter计数器(对字典的扩展,可以继承字典的所有方法)
>>> c2 = collections.Counter('abcdefgaaabbbdddedjdkfljs')>>> c2Counter({ 'd': 6, 'a': 4, 'b': 4, 'e': 2, 'f': 2, 'j': 2, 'c': 1, 'g': 1, 'k': 1, 'l': 1, 's': 1}) #统计每个字符在字符串中出现的次数
常用方法有:
1 >>> c1 = collections.Counter('aacdabc')2 >>> c2 = collections.Counter('aac')3 >>> c14 Counter({ 'a': 3, 'c': 2, 'b': 1, 'd': 1})5 >>> c26 Counter({ 'a': 2, 'c': 1})7 >>> c1.update(c2)8 >>> c19 Counter({ 'a': 5, 'c': 3, 'b': 1, 'd': 1})#更新后次数出现变化
1 >>> c1 = collections.Counter('aacdabc')2 >>> c13 Counter({ 'a': 3, 'c': 2, 'b': 1, 'd': 1})4 Counter({ 'a': 5, 'c': 3, 'b': 1, 'd': 1})5 >>> c1['r']6 0
1 >>> c2 = collections.Counter('aac')2 >>> c23 Counter({ 'a': 2, 'c': 1})4 >>> c2.clear()5 >>> c26 Counter()
1 >>> c1 = collections.Counter('aacdabc')2 >>> c13 Counter({ 'a': 3, 'c': 2, 'd': 1, 'b': 1})4 >>> c1.most_common(3)5 [('a', 3), ('c', 2), ('d', 1)]
1 >>> c1 = collections.Counter('aacdabcasdfete') 2 >>> c1 3 Counter({ 'a': 4, 'c': 2, 'e': 2, 'd': 2, 'b': 1, 'f': 1, 's': 1, 't': 1}) 4 >>> for i in c1.elements(): 5 ... print i 6 ... 7 a 8 a 9 a10 a11 c12 c13 b14 e15 e16 d17 d18 f19 s20 t
2.有序字典OrderedDict,跟普通字典的用法一样(没有fromkeys方法)
>>> o1 = collections.OrderedDict()>>> o1['k1']=1>>> o1['k2']=2>>> o1['k3']=3>>> o1OrderedDict([('k1', 1), ('k2', 2), ('k3', 3)])
3. defaultdict为字典里的值(values)设置一个默认类型
>>> my_dict = collections.defaultdict(list)>>> my_dict['k1'].append(123)>>> my_dictdefaultdict(, { 'k1': [123]})
4.namedtuple可命名元组,对元组进行扩展,给tuple元素添加一个名字,相当于自己创建了一个类
>>> mytuple = collections.namedtuple('mytuple',['x','y'])>>> tu1 = mytuple(1,2)>>> tu1mytuple(x=1, y=2)>>> tu1.x1>>> tu1.y2
5.deque双向队列:
特点:两边都可取可插,线程安全
常用方法:
1 >>> q=collections.deque([1, 11, 123, 1234]) 2 >>> q 3 deque([1, 11, 123, 1234]) 4 >>> q.pop() 5 1234 6 >>> q 7 deque([1, 11, 123]) 8 >>> q.popleft() 9 110 >>> q11 deque([11, 123])
1 >>> q=collections.deque([1, 11, 123, 1234]) 2 >>> q.remove(123)3 >>> q4 deque([1, 11, 1234])
1 >>> q=collections.deque([1, 11, 123, 1234])2 >>> q.append(555)3 >>> q4 deque([1, 11, 123, 1234, 555])5 >>> q.appendleft(222)6 >>> q7 deque([222, 1, 11, 123, 1234, 555])
1 >>> q=collections.deque(['a','b','c','d','e','a','b',]) 2 >>> q3 deque(['a', 'b', 'c', 'd', 'e', 'a', 'b'])4 >>> q.count('b')5 2
1 >>> q=collections.deque(['a','b','c','d','e','a','b',])2 >>> q.extend(['a','b',])3 >>> q4 deque(['a', 'b', 'c', 'd', 'e', 'a', 'b', 'a', 'b'])5 >>> q.extendleft(['b','b','b'])6 >>> q7 deque(['b', 'b', 'b', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'a', 'b'])
1 >>> q=collections.deque(['a','b','c','d','e','a','b',])2 >>> q.index('b')3 1
1 >>> q 2 deque(['a', 'b', 'c', 'd', 'e', 'a', 'b']) 3 >>> q.pop() 4 'b' 5 >>> q 6 deque(['a', 'b', 'c', 'd', 'e', 'a']) 7 >>> q.popleft() 8 'a' 9 >>> q10 deque(['b', 'c', 'd', 'e', 'a'])
1 >>> q=collections.deque(['a','b','c','d','e','a','b',])2 >>> q3 deque(['a', 'b', 'c', 'd', 'e', 'a', 'b'])4 >>> q.remove('c')5 >>> q6 deque(['a', 'b', 'd', 'e', 'a', 'b'])
1 >>> q=collections.deque(['a','b','c','d','e','a','b',])2 >>> q3 deque(['a', 'b', 'c', 'd', 'e', 'a', 'b'])4 >>> q.reverse()5 >>> q6 deque(['b', 'a', 'e', 'd', 'c', 'b', 'a'])
1 >>> q=collections.deque(['a','b','c','d','e','a','b',])2 >>> q3 deque(['a', 'b', 'c', 'd', 'e', 'a', 'b'])4 >>> q.rotate(1)5 >>> q6 deque(['b', 'a', 'b', 'c', 'd', 'e', 'a'])7 >>> q.rotate(3)8 >>> q9 deque(['d', 'e', 'a', 'b', 'a', 'b', 'c'])
6.单向队列
特点: 线程安全,FIFO(先进先出)
>>> import Queue #Python2.x 是Queue,3.x是queue>>> q = Queue.Queue(10)#设置长度>>> q>>> q.put(1) #插数据>>> q.put(2)>>> q.put(3)>>> q.qsize() #计算队列长度3>>> q.get() #取数据1>>> q.get()2>>> q.get()3
深浅拷贝用法
字符串/数字深浅拷贝的结果一样,会共用内存地址空间,所以这里只讨论列表/元组/字典深浅拷贝的差别
浅拷贝:只拷贝第一层,如果拷贝的元组/列表/字典内有嵌套列表/字典时,当嵌套列表/字典修改时,原列表/字典也会被修改。
1 l1 = [11,22,33,[22,33,44]] 2 >>> l2 = l1.copy() 3 >>> l2 4 [11, 22, 33, [22, 33, 44]] 5 >>> l2[3][1] = 'b' 6 >>> l2 7 [11, 22, 33, [22, 'b', 44]] 8 >>> l1 9 [11, 22, 33, [22, 'b', 44]] #当修改嵌套列表时,原列表也会被改变10 >>> l2[0] = 10011 >>> l212 [100, 22, 33, [22, 'b', 44]]13 >>> l114 [11, 22, 33, [22, 'b', 44]]#修改第一层列表时,原列表不改变
1 >>> l1 = [11,22,44,{11:22}]2 >>> l2 = l1.copy()3 >>> l24 [11, 22, 44, {11: 22}]5 >>> l2[3][11] = 'abc' 6 >>> l27 [11, 22, 44, {11: 'abc'}]8 >>> l19 [11, 22, 44, {11: 'abc'}]
1 >>> d1 = {11:11,22:{33:44}}2 >>> d2 = d1.copy()3 >>> d24 {11: 11, 22: {33: 44}}5 >>> d2[22][33] = 'abc'6 >>> d27 {11: 11, 22: {33: 'abc'}}8 >>> d19 {11: 11, 22: {33: 'abc'}}#可以看出字典也是一样的,只能拷贝第一层
1 >>> import copy 2 >>> t1 = (11,22,33,[11,22,33]) 3 >>> t2 = copy.copy(t1) 4 >>> t2 5 (11, 22, 33, [11, 22, 33]) 6 >>> t2[3][1] = 'abc' 7 >>> t2 8 (11, 22, 33, [11, 'abc', 33]) 9 >>> t110 (11, 22, 33, [11, 'abc', 33])
深拷贝:完完全全独立的拷贝,所有层都有独立的内存地址
1 >>> l1 = [11,22,33,[11,22,33]]2 >>> l2 = copy.deepcopy(l1)3 >>> l24 [11, 22, 33, [11, 22, 33]]5 >>> l2[3][0] = 'abc'6 >>> l27 [11, 22, 33, ['abc', 22, 33]]8 >>> l19 [11, 22, 33, [11, 22, 33]]
函数
1.内置函数
内置函数是Python里自带的,本身就可以被调用的函数
常用内置函数有:
1 >>> vars()2 { '__doc__': None, 'd2': {11: 11, 22: {33: 'abc'}}, '__name__': '__main__', 't1': (11, 22, 33, [11, 'abc', 33]), '__builtins__':, 'l2': [11, 22, 33, ['abc', 22, 33]], 'l1': [11, 22, 33, [11, 22, 33]], 't2': (11, 22, 33, [11, 'abc', 33]), '__package__': None, 'a1': 123123, '__spec__': None, 'a2': 123123, 'd1': {11: 11, 22: {33: 'abc'}}, '__loader__': , 'copy': }
vars()函数下需要比较注意的有以下三个:
1 >>> dir()2 ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a1', 'a2', 'copy', 'd1', 'd2', 'i', 'l1', 'l2', 'ret', 't1', 't2', 'x']
reload:重新导入模块
1 >>> max(11,22,33,44)2 44
1 >>> min(22,33,66,33,22)2 22
1 >>> sum([123,532,888]) #sum的参数是列表2 1543
1 >>> pow(2,10)2 1024
1 >>> bool([]) 2 False 3 >>> bool() 4 False 5 >>> bool('') 6 False 7 >>> bool(' ') 8 True 9 >>> bool('a')10 True11 >>> bool([11])12 True
1 #代码 2 li = [] 3 while True: 4 a = input('>>>') 5 if a == 'abc': 6 break 7 else: 8 li.append(a) 9 print(li)10 b = all(li)11 print(b)12 #执行结果13 >>>1114 >>>2215 >>>16 >>>abc17 ['11', '22', '']18 False
1 #代码 2 li = [] 3 while True: 4 a = input('>>>') 5 if a == 'abc': 6 break 7 else: 8 li.append(a) 9 print(li)10 b = any(li)11 print(b)12 #执行结果13 >>>1114 >>>2215 >>>16 >>>abc17 ['11', '22', '']18 True
1 >>> ord('a') 2 973 >>> ord('A')4 65
1 >>> chr(65)2 'A'3 >>> chr(97)4 'a'
1 >>> hex(16)2 '0x10'
1 >>> oct(16)2 '0o20'
1 >>> bin(16)2 '0b10000'
1 >>> li = [11,22,33,44,55]2 >>> for index,i in enumerate(li):3 ... print(index,i)4 ...5 (0, 11)6 (1, 22)7 (2, 33)8 (3, 44)9 (4, 55)
1 #代码2 def fun(x):3 return x + 1004 li = [11,22,33,44]5 #li2 = tuple(map(lambda x:x+100,li))6 li2 = tuple(map(fun,li))7 print(li2)8 #执行结果9 (111, 122, 133, 144)
1 >>> li = [11,22,33,44] 2 >>> def func(x): 3 ... if x>33: 4 ... return True 5 ... else: 6 ... return False 7 ... 8 >>> a = filter(func,li) 9 >>> list(a)10 [44]
1 >>> round(8.8)2 9
1 >>> x = [1,2,3] 2 >>> y = [4,5,6,7,] 3 >>> zipped = zip(x,y) 4 >>> zipped 56 >>> list(zipped) 7 [(1, 4), (2, 5), (3, 6)] 8 >>> x2 , y2 = zip(*zip(x,y)) 9 >>> list(x2) == x10 True11 >>> list(y2) == y12 False
2.自定义函数
def 函数名(参数):...函数体...return
>>> def show(a,b=123): #默认参数为b... print(a,b)... >>> show(999) #如果只有一个参数,b自动填充999 123>>> show(999,888)#如果有两个参数,b的默认值无效999 888
>>> def show(a,b):... print(a,b)... >>> show(b=123,a=222)222 123
1 >>> def show(*args):2 ... print(args,type(args))3 ... 4 >>> show(1,2,3,)5 (1, 2, 3)6 >>>
1 >>> def show(**args): 2 ... print(args,type(args))3 ... 4 >>> show(a = 11,b = 12,c = 13)5 { 'c': 13, 'b': 12, 'a': 11}
def show(*args,**kwargs): print(args,type(args)) print(kwargs,type(kwargs))l = [11,22,33,44]d = { 'n1':88,'n2':99}show(*l,**d)show(l,d)show(11,22,33,44,n1 = 88,n2 = 99)
执行结果:
(11, 22, 33, 44){ 'n2': 99, 'n1': 88} ([11, 22, 33, 44], { 'n2': 99, 'n1': 88}) {} (11, 22, 33, 44) { 'n2': 99, 'n1': 88}
s1 = '{name} is {type}'# s1 = '{0} is {1}'# s2 = s1.format('akon','goodboy')# l = ['akon','goodboy']# s2 = s1.format(*l)d = { 'name':'akon','type':'goodboy'}s2 = s1.format(**d)print(s2)
akon is goodboy
>>> func = lambda a: a+1
>>> ret = func(20)>>> print(ret)21
文件常用操作:
read(),可以指定从当前指针位置往后读取多少个字节,如果不指定,读取当前指针后所有内容
tell()显示当前指针位置
seek()指定当前指针位置
truncate()截取指针前面的内容,放弃指针后面的内容