天天看點

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)]
      

繼續閱讀