python ---- collections模块
2019-07-26 22:45
85 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/adrian_boy/article/details/97430270
collections模块:
-
1.namedtuple: 生成可以使用名字来访问元素内容的tuple
from collections import namedtuple,deque Point = namedtuple('tu',["a","b","c"]) # 第一个参数是元组的名字,第二参数是元组中元素的[名字,名字] p = Point({"keu":(1,2,3,4)}, 20,10) print(p) #结果: tu(a={'keu': (1, 2, 3, 4)}, b=20, c=10) tu = (1,2,32,34,4) # 普通元组 print(tu) #结果: (1, 2, 32, 34, 4)
-
2.deque: 双端队列,可以快速的从另外一侧追加和推出对象
from collections import namedtuple,deque lst = deque([1,2,3,4,5,6,7]) lst.append(8) print(lst) #结果: deque([1, 2, 3, 4, 5, 6, 7, 8]) lst.appendleft(0) print(lst) #结果: deque([0, 1, 2, 3, 4, 5, 6, 7, 8]) lst.pop() print(lst) #结果: deque([0, 1, 2, 3, 4, 5, 6, 7]) lst.popleft() print(lst) print(lst[4]) #结果: deque([1, 2, 3, 4, 5, 6, 7]) 5
-
3.Counter: 计数器,主要用来计数
from collections import Counter s = "1112233344aaa" s = [1,1,2,2,3,3] s = (1,2,3,3,4,5,6,7,78) print(dict(Counter(s))) # *** #结果: {1: 1, 2: 1, 3: 2, 4: 1, 5: 1, 6: 1, 7: 1, 78: 1} #统计元素出现的次数
-
4.OrderedDict: 有序字典
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
如果要保持Key的顺序,可以用OrderedDict:from collections import OrderedDict d = dict([('a', 1), ('b', 2), ('c', 3)]) # 另一种定义字典的方式 print(d) #结果: {'a': 1, 'c': 3, 'b': 2} od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print(od) #结果: OrderedDict([('a', 1), ('b', 2), ('c', 3)])
-
5.defaultdict: 带有默认值的字典
from collections import defaultdict dic = defaultdict(list) dic["k1"].append(12) print(dic) #结果: defaultdict(<class 'list'>, {'k1': [12]})
from collections import defaultdict dic = defaultdict(set) li = [11,22,33,44,55,77,88,99,90] for i in li: if i > 66: dic["k1"].add(i) else: dic["k2"].add(i) print(dic) #结果: defaultdict(<class 'set'>, {'k2': {33, 11, 44, 22, 55}, 'k1': {88, 90, 99, 77}})
from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' # key1存在 print(dd['key1']) dd['key2'] # key2不存在,返回默认值 print(dd['key2']) #结果: abc N/A
相关文章推荐
- Python collections 模块用法举例
- python collections 模块
- Python——collections模块
- 简单掌握Python的Collections模块中counter结构的用法
- Python内建模块--collections
- [从头学python] 第04节 集合模块collections
- python模块 - collections模块
- Python模块: collections
- python模块collections中namedtuple()的理解
- Python学习笔记(三十三)常用内置模块(2)collections_namedtuple_deque_defaultdict_OrderedDict_Counter
- python模块之collections
- python-day20--collections模块
- Python算法和数据结构(一)——collections模块
- Python模块: collections
- Python基础之collections模块
- 简单掌握Python的Collections模块中counter结构的用法
- Python系列之Collections内置模块(2)
- python模块collections中namedtuple()的理解
- python模块知识三 hashlib 加密模块、collections、re模块
- Python常用模块re,collections,random