namedtuple
# namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
# 用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用
Coord = collections.namedtuple("Coord", ["x", "y"])
p = Coord(1, 2)
print(p.x, p.y) # 1 2
print(isinstance(p, Coord), isinstance(p, tuple)) # True True
deque
# deque 是为了高效实现插入和删除操作的双向列表,适合用于队列和栈
q = collections.deque(["a", "b", "c"], maxlen=10)
q.append("x")
q.appendleft("y")
print(type(q)) # <class 'collections.deque'>
print(list(q)) # ['y', 'a', 'b', 'c', 'x']
q.pop()
q.popleft()
print(list(q)) # ['a', 'b', 'c']
qc = q.copy() # 浅拷贝
print(list(qc)) # ['a', 'b', 'c']
q.extend(["d", "e"])
q.extendleft(["0"])
q.insert(1, "1")
print(q.index("d")) # 5
print(q.count("d")) # 1
q.remove("d")
print(list(q)) # ['0', '1', 'a', 'b', 'c', 'e']
q.rotate() # 向右循环移动1个元素
print(list(q)) # ['e', '0', '1', 'a', 'b', 'c']
q.rotate(3) # 向右循环移动n个元素
print(list(q)) # ['a', 'b', 'c', 'e', '0', '1']
q.reverse()
print(list(q)) # ['1', '0', 'e', 'c', 'b', 'a']
q.clear()
print(list(q)) # []
defaultdict
# defaultdict key不存在时,返回一个默认值,其它行为和dict完全一致
dd = collections.defaultdict(lambda: "NA")
print(type(dd)) # <class 'collections.defaultdict'>
dd["a"] = 1
print(dd["a"], dd["b"]) # 1 NA
dd = collections.defaultdict(list)
dd2 = collections.defaultdict(int)
colors = [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]
for k, v in colors:
dd[k].append(v)
dd2[k] += 1
print(dict(dd)) # {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}
print(dict(dd2)) # {'yellow': 2, 'blue': 2, 'red': 1}
ChainMap
# ChainMap 可以把一组dict串起来并组成一个逻辑上的dict。查找的时候,会按照顺序在内部的dict依次查找。
combined = collections.ChainMap({"a": 1}, {"a": 2, "b": 2}, {"c": 3})
print(combined["a"], combined["b"], combined["c"]) # 1 2 3
Counter
# Counter 计数
c = collections.Counter({"a": 2, "b": 3, "c": 1})
print(c) # Counter({'b': 3, 'a': 2, 'c': 1})
c = collections.Counter(a=2, b=3, c=1)
print(c) # Counter({'b': 3, 'a': 2, 'c': 1})
c = collections.Counter()
for i in "acdffdaaaddccc":
c[i] += 1
print(c) # Counter({'a': 4, 'c': 4, 'd': 4, 'f': 2})
print(isinstance(c, dict)) # True
c2 = collections.Counter("acdffdaaaddccc")
c2.update("acc")
print(c2) # Counter({'c': 6, 'a': 5, 'd': 4, 'f': 2})
c3 = collections.Counter(["red", "blue", "red", "green", "blue", "blue"])
print(dict(c3)) # {'red': 2, 'blue': 3, 'green': 1}
print(list(c3.elements())) # ['red', 'red', 'blue', 'blue', 'blue', 'green']
print(sorted(c3.elements())) # ['blue', 'blue', 'blue', 'green', 'red', 'red']
print(c3.most_common(2)) # [('blue', 3), ('red', 2)] 返回前n个最多的数据
print(dict(c2 - c)) # {'a': 1, 'c': 2}
print(dict(c2 + c)) # {'a': 9, 'c': 10, 'd': 8, 'f': 4}
标签:blue,Counter,list,print,collections,python3,集合,red From: https://www.cnblogs.com/caroline2016/p/18454532