python实例:快速找出多个字典中的公共键

1.生成随机字典

# 从abcdefg 中随机取出 3-6个,作为key, 1-4 的随机数作为 value
s1 = {x : randint(1, 4) for x in sample('abcdefg', randint(3, 6))}

方法1 用集合方法

s1 = {'c': 3, 'f': 3, 'g': 3, 'd': 4, 'b': 2}
s2 = {'b': 3, 'f': 2, 'c': 2}
s3 = {'f': 3, 'b': 1, 'c': 4, 'd': 3, 'g': 1, 'e': 2}


print( s1.keys() & s2.keys() & s3.keys()) # {'f', 'b', 'c'}

方法2 使用 map 和 reduce

# map()将函数调用映射到每个序列的对应元素上并返回一个含有所有返回值的列表

# reduce函数对参数序列中元素进行累计计算

from functools import reduce
s1 = {'c': 3, 'f': 3, 'g': 3, 'd': 4, 'b': 2}
s2 = {'b': 3, 'f': 2, 'c': 2}
s3 = {'f': 3, 'b': 1, 'c': 4, 'd': 3, 'g': 1, 'e': 2}

ret = reduce(lambda x, y : x & y,  map(dict.keys, [s1, s2, s3]))
print(ret)

猜你喜欢

转载自www.cnblogs.com/appleat/p/10033011.html