案例
代码
from random import randint, sample
p = sample('abcdefg', 3) # 7个字符中,随机取样3个
p2 = sample('abcdefg', randint(3, 6)) # 7个字符中,随机取样3-6个
# print(p, p2, sep="\n==========\n")
r1 = {x: randint(1, 4) for x in sample('abcdefgh', randint(3, 6))}
r2 = {x: randint(1, 4) for x in sample('abcdefgh', randint(3, 6))}
r3 = {x: randint(1, 4) for x in sample('abcdefgh', randint(3, 6))}
print(r1, r2, r3, sep="\n============\n")
# 原始方法
res = []
for k in r1:
if k in r2 and k in r3:
res.append(k)
# print(res)
print("-"*80)
# set集合方法 &
print(r1.keys(), r2.keys(), r3.keys(), sep="\n=======\n") # Python2中为dict.viewkeys
print(r1.keys() & r2.keys() & r3.keys()) # &:set集合之间的交集, 但是当数据源为海量时,这样的方法显然还不行
# map reduce
from functools import reduce # Python3中,reduce函数需要import才可以使用
print(reduce(lambda a, b: a & b, map(dict.keys, [r1, r2, r3])))