python——collections容器

用collections.__all__查看所有的子类,一共包含9个

import collections
print(collections.__all__)
['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 
'UserString', 'Counter', 'OrderedDict', 'ChainMap']

# import collections
# help(collections)

deque

#deque, 类似列表(list)的容器,实现了在两端快速添加(append)和弹出(pop)
from  collections import deque
d = deque('ghi')
d.append('j')       # 在右边添加元素
d.appendleft('f')   # 在左边添加元素
print(d)
print(d.pop())      # 弹出右边的元素
print(d.popleft())  # 弹出左边的元素
#rotate的主要目的就是将【first~middle】的元素和【middle~last】的元素互换位置,middle所指向的元素会成为整个容器的第一个元素。
# 逆时针旋转2次
d.rotate(2)
print(d)
# 顺时针旋转2次
d.rotate(-2)
print(d)

输出

deque(['f', 'g', 'h', 'i', 'j'])
j
f
deque(['h', 'i', 'g'])
deque(['g', 'h', 'i'])

ChainMap

# ChainMap
# 将多个字典或者其他映射组合在一起,创建一个单独的可更新的视图
# 如果没有指定maps,就提供一个默认的空字典,这样一个新链至少有一个映射
from collections  import ChainMap
baseline = {'BookName': 'python', 'Price': '39'}
adjustments = {'Price': '49', 'Press': 'Tsinghua Press'}
newmap = ChainMap(adjustments, baseline)
print(newmap['Price'])
print(newmap['Press'])

输出

49
Tsinghua Press

Counter

# Counter, 是一个自带你的子类,用于计数可哈希对象
from collections import Counter
c = Counter('abcdeabcdabcaba')  # 字符串可迭代对象
c = Counter({'red': 4, 'blue': 2, 'yellow': 3}) # 字典映射
c = Counter(cats=4, dogs=8) #关键字参数
print(c)
print(c['blue'])
print(c['black'])   # 如果引用的键没有任何记录,就返回一个0,而不是弹出一个 KeyErroe
print(c['cats'])

输出

Counter({'dogs': 8, 'cats': 4})
0
0
4

OrderedDict

# OrderedDict是一个有序字典,key是按照插入的顺序排列,不是key本身排序
from collections import OrderedDict
d = OrderedDict.fromkeys('edcba')
print(d.popitem())
print(d)
d.move_to_end('c')
print(d)
''.join(d.keys())

输出

('a', None)
OrderedDict([('e', None), ('d', None), ('c', None), ('b', None)])
OrderedDict([('e', None), ('d', None), ('b', None), ('c', None)])

posted @ 2022-07-13 19:16  hcypeu  阅读(51)  评论(0)    收藏  举报