前言
嗨喽~大家好呀,这里是魔王呐 ❤ ~!
python更多源码/资料/解答/教程等 点击此处跳转文末名片免费获取
方法一:for in循环
from random import randint, sample
a1 = {k: randint(1, 4) for k in 'abcdefg'}
a2 = {k: randint(1, 4) for k in 'abc123456789'}
a3 = {k: randint(1, 4) for k in 'abcinubububu'}
a4 = {k: randint(1, 4) for k in 'abc89898989'}
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间随机取一个数
方法二:利用集合的交集操作
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:926207505
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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;
尾语
最后感谢你观看我的文章呐~本次航班到这里就结束啦 🛬
希望本篇文章有对你带来帮助 🎉,有学习到一点知识~
躲起来的星星🍥也在努力发光,你也要努力加油(让我们一起努力叭)。