[Python高效编程] - 快速找到多个字典的公共键

开发环境

  1. Python版本: python3.6
  2. 调试工具:pycharm 2017.1.3
  3. 电脑系统:Windows 10 64位系统

使用随机数生成数据

from random import randint, sample

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))}

print(s1)
print(s2)
print(s3)
{'f': 1, 'd': 3, 'e': 4, 'a': 2, 'g': 2}
{'b': 1, 'e': 3, 'f': 3, 'g': 3, 'd': 4, 'c': 1}
{'e': 3, 'b': 2, 'f': 3, 'c': 3, 'g': 4}

找出公共键

使用迭代方法

from random import randint, sample

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))}

print(s1)
print(s2)
print(s3)

res = []
for k in s1:
    if k in s2 and k in s3:
        res.append(k)

print(res)
{'e': 1, 'a': 1, 'd': 1, 'g': 3}
{'a': 2, 'e': 2, 'd': 3, 'c': 4, 'f': 1, 'g': 4}
{'a': 1, 'd': 2, 'f': 3, 'b': 4, 'c': 4, 'e': 1}
['e', 'a', 'd']

使用集合操作

from random import randint, sample

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))}

print(s1)
print(s2)
print(s3)

# 使用集合操作
res1 = s1.keys() & s2.keys() & s3.keys()
print(res1)
{'c': 2, 'e': 1, 'a': 1, 'g': 2}
{'e': 1, 'c': 3, 'b': 4, 'a': 3, 'g': 3}
{'g': 1, 'b': 2, 'f': 2, 'a': 4}
{'a', 'g'}

使用map函数和reduce函数处理

from functools import reduce
from random import randint, sample

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))}

print(s1)
print(s2)
print(s3)

# 使用map函数和reduce函数
res2 = reduce(lambda a,b: a&b, map(dict.keys, [s1, s2, s3]))
print(res2)
{'d': 2, 'c': 2, 'f': 1}
{'c': 4, 'e': 3, 'g': 3, 'b': 1, 'd': 3, 'f': 1}
{'c': 3, 'b': 4, 'g': 2}
{'c'}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值