您的位置:首页 > 编程语言 > Python开发

python-3-如何快速找到多个字典中的公共键(key)?

2017-04-20 09:11 387 查看


普通方案1:

from random import randint,sample

sample('abcdefg',randint(3,6))
# 字典解析
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))}
res = []
# 在s1中迭代,并且判断是否在是s2和s3中
for k in s1:
if k in s2 and k in s3:
res.append(k)
print(s1)
print(s2)
print(s3)
print(res)


普通方案2:





那么如果是N轮,可以使用map或者reduce函数

reduce(lambda a,b: a & b, map(dict.viewkeys,[s1,s2,s3,.....]))


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: