问题5:如何快速找到多个字典中的公共键(key)
方法一:for in循环
from random import randint, sample
a1 = {k; randint(1, 4) for k in 'abcdefg'}
a2 = {k; randint(1, 4) for k in 'abcdefg'}
a3 = {k; randint(1, 4) for k in 'abcdefg'}
a4 = {k; randint(1, 4) for k in 'abcdefg'}
r = []
for x in a1:
if x in a2 and x in a3 and x in a4:
r.append(x)
print(r)
- randint(1, 4):从1~4间随机取一个数;
方法二:利用集合的交集操作
from random import randint, sample
a1 = {k; randint(1, 4) for k in 'abcdefg'}
a2 = {k; randint(1, 4) for k in 'abcdefg'}
a3 = {k; randint(1, 4) for k in 'abcdefg'}
a4 = {k; randint(1, 4) for k in 'abcdefg'}
a = a1.keys() & a2.keys() & a3.keys() & a4.keys()
print(a)
- a1.keys():得到a1字典的key,一set格式;
- a1.keys() & a2.keys() & a3.keys() & a4.keys():取4个集合的公共元素;
- a为一个集合(set)
方法三:使用map即reduce(用于求n个字典的公共key)
from random import randint, sample
from functools import reduce
a1 = {k; randint(1, 4) for k in 'abcdefg'}
a2 = {k; randint(1, 4) for k in 'abcdefg'}
a3 = {k; randint(1, 4) for k in 'abcdefg'}
a4 = {k; randint(1, 4) for k in 'abcdefg'}
b1 = map(dict.keys, [a1, a2, a3, a4])
b2 = reduce(lambda a ,b: a & b, b1)
print(b2)
- b1 = map(dict.keys, [a1, a2, a3, a4]):以集合形式取每个字典的keys;