如何统计序列中元素的频度
import random
import collections
numbers = [random.randint(1,20) for _ in range(60)]
print(numbers)
counter = collections.Counter(numbers)
print(counter)
counter_dict = dict(counter)
print(counter_dict)
result = sorted(counter_dict.items(),key= lambda item:item[1],reverse=True)
print(result)
如何快速找到多个字典中的公共键
import random
from functools import reduce
d1 = {x: random.randint(1,4) for x in random.sample('abcdef',random.randint(1,5))}
d2 = {x: random.randint(1,4) for x in random.sample('abcdef',random.randint(1,5))}
d3 = {x: random.randint(1,4) for x in random.sample('abcdef',random.randint(1,5))}
d4 = {x: random.randint(1,4) for x in random.sample('abcdef',random.randint(1,5))}
lst = [d1,d2,d3,d4]
print(lst)
h = map(lambda x: x.keys(),lst)
result = reduce(lambda x, y: x & y, h)
print(list(result))
如何让字典保持有序
import collections
diction = collections.OrderedDict()
diction['a'] = 1
diction['b'] = 2
diction['c'] = 3
print(diction)