python3 50个练习例子之快速找到多个字典中的公共键

  1. 第一种
from random import randint
from random import sample

s1 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))} # 推导表达式+随机数生成字典值
print(s1) # {'g': 4, 'b': 4, 'f': 2, 'a': 3, 'd': 2}
s2 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
print(s2) # {'d': 3, 'g': 2, 'b': 3, 'e': 2, 'c': 3}
s3 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
print(s3) # {'f': 1, 'a': 4, 'c': 2, 'g': 2, 'b': 2, 'e': 2}
s4 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
print(s4) # {'c': 3, 'f': 2, 'g': 2, 'b': 4, 'e': 3, 'd': 3}

sKey = s1.keys() & s2.keys() & s3.keys() & s4.keys()
print(sKey) # {'g', 'b'}
  1. 第二种
from random import randint
from random import sample
from functools import reduce

s1 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))} # 推导表达式+随机数生成字典值
print(s1) # {'g': 4, 'b': 4, 'f': 2, 'a': 3, 'd': 2}
s2 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
print(s2) # {'d': 3, 'g': 2, 'b': 3, 'e': 2, 'c': 3}
s3 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
print(s3) # {'f': 1, 'a': 4, 'c': 2, 'g': 2, 'b': 2, 'e': 2}
s4 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
print(s4) # {'c': 3, 'f': 2, 'g': 2, 'b': 4, 'e': 3, 'd': 3}

a = map(dict.keys,[s1,s2,s3,s4])
b = reduce(lambda x,y:x & y,a)
print(b) # {'g', 'b'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值