Python进阶学习(2)

如何统计序列中元素的频度

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)        #将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)

# 对于列表中的每一项元素,都进行取出他们所有 key 的操作
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)

你可能感兴趣的:(Python学习笔记,python,random)