'''
目的:筛选出N个字典中都出现相同的键
'''
#方法一:for循环(执行效率低)
from random import randint,sample
d1 = {x:randint(1,6) for x in sample(['aa','bb','cc','dd','ee'],randint(1,5))}
d2 = {x:randint(1,6) for x in sample(['aa','bb','cc','dd','ee'],randint(1,5))}
d3 = {x:randint(1,6) for x in sample(['aa','bb','cc','dd','ee'],randint(1,5))}
print(d1)
print(d2)
print(d3)
res = []
for x in d1:
if x in d2 and x in d3:
res.append(x)
print(res)
#方法二:高阶函数 map + reduce
from random import randint,sample
from functools import reduce
d1 = {x:randint(1,6) for x in sample(['aa','bb','cc','dd','ee'],randint(1,5))}
d2 = {x:randint(1,6) for x in sample(['aa','bb','cc','dd','ee'],randint(1,5))}
d3 = {x:randint(1,6) for x in sample(['aa','bb','cc','dd','ee'],randint(1,5))}
print(d1)
print(d2)
print(d3)
#将每个字典中的 键 筛选出来
r = map(dict.keys, [d1,d2,d3])
print(list(r))
#reduce迭代筛选(每次&运算后的结果作为x的新值,效率高)
res = reduce(lambda x , y : x & y ,map(dict.keys, [d1,d2,d3]))
print(res)
'''
提问与思考:
1、 直接遍历字典只能遍历键key,items() 函数以列表返回可遍历的(键, 值) 元组数组
2、reduce的传入函数必须接收两个参数
'''