姚聚团,威泰格,粽子怎么包
collections模块主要封装了一些关于集合类的相关操作。比如,iterable,iteratort等等,除此之外,collections还提供了一些除基本数据类型以外的数据集合类型。counter,deque,orderdict,defaultdict以及namedtuple
from collections import counter s = "hello word" print(counter(s)) # counter({'l': 2, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}) lst = [11, 22, 33, 44, 55, 66, 55, 44, 44] el = counter(lst) print(el[44]) # 3
from collections import deque q = deque() q.append(11) q.append(22) q.appendleft(33) print(q) # deque([33, 11, 22]) print(q[0]) # 33 print(q.pop()) # 22 print(q.popleft()) # 33
from collections import namedtuple nt = namedtuple("point", ["x", "y"]) p = nt(1, 2) print(p.x) # 1 print(p.y) # 2
from collections import defaultdict dic1 = defaultdict(list) print(dic1["name"]) # [] print(dic1) # defaultdict(<class 'list'>, {'name': []}) def func(): return 'tom' dic = defaultdict(func) print(dic["name"]) # tom
应用:
# 将lst = [11, 22, 33, 44, 55, 66, 77, 88, 99]大于等于66放入字典"key1"中,小于66放入字典"key2"中 from collections import defaultdict lst = [11, 22, 33, 44, 55, 66, 77, 88, 99] dic = defaultdict(list) for el in lst: if el < 66: dic["key2"].append(el) else: dic["key1"].append(el) dic = dict(dic) print(dic) # {'key2': [11, 22, 33, 44, 55], 'key1': [66, 77, 88, 99]}
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python爬虫:Request Payload和Form Data的简单区别说明
浅谈Python中threading join和setDaemon用法及区别说明
Python3-异步进程回调函数(callback())介绍
python继承threading.Thread实现有返回值的子类实例
Python中使用threading.Event协调线程的运行详解
网友评论