当前位置:主页 > 软件编程 > Python代码 >

Python查找多个字典公共键key的方法

时间:2022-08-04 10:03:41 | 栏目:Python代码 | 点击:

1、如何快速找到多个字典中的公共键(key)

实际案例:

西班牙足球甲级联赛,每轮球员进球统计:

 统计出前N轮,每场比赛都有进球的球员。

注:公共键就是在每个字典中都出现的键。

解决方案:

利用集合(set)的交集操作

2、代码演示

from random import randint, sample 
# 随机取样进球球员信息
print(sample('abcdef', randint(3, 6)))
# 字典解析产生每轮数据
s1 = {x: randint(1, 4) for x in sample('abcdef', randint(3, 6))}
s2 = {x: randint(1, 4) for x in sample('abcdef', randint(3, 6))}
s3 = {x: randint(1, 4) for x in sample('abcdef', randint(3, 6))}
print(s1, s2, s3)
# 方法1:
# 迭代第1轮中键,之后再去判断这个key是否在s2和s3当中,如果在就表示这个键是公共键
res = []
for k in s1:
    if k in s2 and k in s3:
        res.append(k)
print(res)
 
# 方法2:
# 获取每一个字典中的所有key,python2为viewkeys()
print(s1.keys(), s2.keys(), s3.keys())
# 取所有集合的&交集,就是公共键
print(s1.keys() & s2.keys() & s3.keys())
 
# 方法3:
# 使用map得到每一轮的keys集合
print(list(map(dict.keys, [s1, s2, s3])))
 
from functools import reduce
# 使用reduce函数,取每一轮的keys集合的交集
print(reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3])))

3、快速找到多个字典中的公共键(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 '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间随机取一个数

方法二:利用集合的交集操作

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;

您可能感兴趣的文章:

相关文章