天天看点

Pyhton编程:collections集合模块命名元组双端队列(double-end queue)有序字典计数器

命名元组

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

p = Point(3, 4)
print(p.x)  # 3
print(p.y)  # 4      

双端队列(double-end queue)

from collections import deque

d = deque([1, 2, 3, 4, 5])

d.append(6)
d.appendleft(0)
print(d)
# deque([0, 1,  2, 3, 4, 5, 6])      

有序字典

from collections import OrderedDict

od = OrderedDict()
od["x"] = 1
od["y"] = 2
od["z"] = 3

print(od)
# OrderedDict([('x', 1), ('y', 2), ('z', 3)])      

计数器

from collections import Counter

s = "abcdavbdafsdfasd"
c = Counter(s)
print(c)
# Counter({'a': 4, 'd': 4, 'b': 2, 'f': 2, 's': 2, 'c': 1, 'v': 1})

print(c.most_common())
# [('a', 4), ('d', 4), ('b', 2), ('f', 2), ('s', 2), ('c', 1), ('v', 1)]
      

继续阅读