目录
Counter:计数器
deque:双端队列
defaultdict:有默认值的字典
OrderedDict:有序字典
之前不用Counter需要这样写:
a=["apple","banana","apple","cat","cat","cat","dog"]
# 通过字典来存储
b={}
for x in a:
b[x] = b.get(x,0) + 1 #b[x]改value
print(b)
# {'apple': 2, 'banana': 1, 'cat': 3, 'dog': 1}
用collections:
from collections import Counter
a = ["apple", "banana", "apple", "cat", "cat", "cat", "dog"]
b = Counter(a)
print("type(b)=", type(b))
print("b=", b)
# type(b)=
# b= Counter({'cat': 3, 'apple': 2, 'banana': 1, 'dog': 1})
from collections import Counter
a = Counter("helloworld")
print("a = ", a)
# a = Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})
print("Top 2: ", a.most_common(2))
# Top 2: [('l', 3), ('o', 2)]
print("a.elements() = ", a.elements())
print("all elements = ", list(a.elements())) # 将计数器还原回原来的内容,但是元素内容会改变
# a.elements() =
# all elements = ['h', 'e', 'l', 'l', 'l', 'o', 'o', 'w', 'r', 'd']
# 和字典的相同点:
print(a.keys())
print(a.values())
# dict_keys(['h', 'e', 'l', 'o', 'w', 'r', 'd'])
# dict_values([1, 1, 3, 2, 1, 1, 1])
a.clear()
print("a = ", a)
# a = Counter()
from collections import Counter
c = Counter(a=3,b=1)
d = Counter(a=2,b=2)
print("c+d =",c+d)
print("c-d =",c-d)
print("c&d =",c&d)
print("c|d =",c|d)
# c+d = Counter({'a': 5, 'b': 3})
# c-d = Counter({'a': 1})
# c&d = Counter({'a': 2, 'b': 1})
# c|d = Counter({'a': 3, 'b': 2})
clear、copy、count、index、reverse和 list的方法都一样
rotate是 deque特有的
from collections import deque
a = deque([1,2,3,4,5])
# 向右循环移动:
a.rotate(1)
print("a = ", a)
# a = deque([5, 1, 2, 3, 4])
a.rotate(2)
print("a = ", a)
# a = deque([3, 4, 5, 1, 2])
# 向左循环移动:
a.rotate(-3)
print("a = ", a)
# a = deque([1, 2, 3, 4, 5])
from collections import defaultdict
# d={}
# print(d['x']) 字典内没有x,则会报错
d = defaultdict(int)
print(d['x'])
d = defaultdict(list)
print(d['x'])
d = defaultdict(set)
print(d['x'])
d = defaultdict(dict)
print(d['x'])
# 0
# []
# set()
# {}
python版本升级到3.7之后,dict字典对于元素的删除(pop),是依次删最后一个元素,之前版本是随机删除一个。OrderedDict可以指定删除元素的位置,默认是删最后一个元素,如果设置参数如Last=False,则会删除第一个元素。
此外OrderedDict还可以移动键值对的位置