1 # encoding:utf-8 2 # 3 """ @version:1.0 4 @author Heng 5 @time: 6/24/2016 4:52 PM 6 7 """ 8 9 ‘‘‘ 10 collections 是python内建的集合模块 11 12 学习一些常用的函数 13 ‘‘‘ 14 # namedtuple 用于创建一个自定义的tuple对象 15 16 from collections import namedtuple 17 18 # 定义一个2维坐标 19 Point = namedtuple(‘Point‘, [‘x‘, ‘y‘]) 20 p = Point(1, 3) 21 print p.x, p.y 22 # result 1 3 23 # 定义一个圆 24 # namedtuple(‘名称‘, [属性list]): 25 Circle = namedtuple(‘circle‘, [‘x‘, ‘y‘, ‘r‘]) 26 c = Circle(1, 1, 3) 27 print c.x, c.y, c.r 28 # result 1 1 3 29 30 31 # deque 提高插入与删除操作的list,适用于队列和栈 32 33 from collections import deque 34 35 q = deque(range(10)) 36 q.append(‘x‘) 37 q.appendleft(‘x1‘) 38 print q 39 # result deque([‘x1‘, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ‘x‘]) 40 41 42 # defaultdict 与dict一样,解决key 不存在时的情况,返回一个默认值 43 44 from collections import defaultdict 45 46 dd = defaultdict(lambda: ‘key not found‘) 47 print dd[‘key‘] 48 49 # result key not found 50 51 # Counter 一个计数器 52 53 from collections import Counter 54 55 c = Counter() 56 for char in "my name is niu,what‘s your name": 57 c[char] = c[char] + 1 58 print c 59 60 # result 统计出字符出现的个数 61 # Counter({‘ ‘: 5, ‘a‘: 3, ‘m‘: 3, ‘n‘: 3, ‘e‘: 2, ‘i‘: 2, ‘s‘: 2, ‘u‘: 2, ‘y‘: 2, "‘": 1, ‘h‘: 1, ‘,‘: 1, ‘o‘: 1, ‘r‘: 1, ‘t‘: 1, ‘w‘: 1}) 62 63 # OrderedDict 一个有序的dict功能 64 65 from collections import OrderedDict 66 67 d = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4, ‘‘: 5} 68 print d # result{‘a‘: 1, ‘c‘: 3, ‘b‘: 2, ‘e‘: 5, ‘d‘: 4} 默认dict是无序的集合 69 70 b = OrderedDict(d) 71 print b 72 73 #result {‘a‘: 1, ‘‘: 5, ‘c‘: 3, ‘b‘: 2, ‘d‘: 4} 74 # OrderedDict([(‘a‘, 1), (‘‘, 5), (‘c‘, 3), (‘b‘, 2), (‘d‘, 4)])
时间: 2024-10-14 06:21:57