"""
第一轮:{'a': 1, 'b': 2}
第二轮:{'c': 1, 'd': 2}
... ...
统计出钱N轮,每场比赛都有进球的球员
"""
方法一:(效率低)
随机产生进球成员(随机取样)
s = sample('abcdefg', randint(3, 6))
print s
s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
print s1
print s2
print s3
获取公共键 res
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
print res
方法二:集合操作
"""
1.使用字典的viewkeys()方法,得到一个字典keys的集合
2.使用map函数,得到所有字典的keys的集合
3.使用reduce函数,取所有的字典的keys的集合的交集
"""
s1.viewkeys()
输出:
dict_keys(['a', 'b', 'f'])
两轮的keys集合:
s1.viewkeys() & s2.viewkeys()
N轮的keys集合:
map(dict.viewkeys, [s1, s2, s3])
所有的字典的keys的集合的交集:
reduce(lambda a, b: a & b, map(dict.viewkeys, [s1, s2, s3]))