python数据结构-如何快速找到多个字典中的公共键
如何快速找到多个字典中的公共键
问题举例
统计每轮都进球的球员:
第1轮{‘tom’:1, 'meixi':2}
第2轮{‘coco’:3, 'meixi':4, 'marton':2}
第3轮{'coco':2, 'meixi':1, 'david':1}
for循环、列表解析和set交集
from random import randint, sample d1 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))} d2 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))} d3 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))} print(d1, d2, d3) print("\n(1)for loop") res1 = [] for key in d1: if key in d2 and key in d3: res1.append(key) print(res1) print("\n(2)list comprehension") res = [k for k in d1 if k in d2 and k in d3] print(res) print("\n(3)set intersection") s1 = d1.keys() s2 = d2.keys() s3 = d3.keys() res3 = s1 & s2 & s3 print(res3)
分析:在实际场景中我们并不知道有几轮,我们需要更通用的一种方法
我们把字典放在列表中,这里仅以三个字典为例,当然列表中可以放n个字典
通用方法(两种)
from random import randint, sample from functools import reduce d1 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))} d2 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))} d3 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))} print(d1, d2, d3) d_list = [d1, d2, d3] print("\nsolution1:") res1 = [k for k in d_list[0] if all(map(lambda d: k in d, d_list[1:]))] print(res1) print("\nsolution2:") res2 = reduce(lambda a, b: a & b, map(dict.keys, d_list)) print(res2)
参考资料:python3实用编程技巧进阶