热线电话:13121318867

登录
2019-03-12 阅读量: 592
如何快速找到多个字典的公共键

sample(seq, n)从序列seq中选择n个随机且不相同的元素;

一般的方法,但是效率不高

from random import randint, sample

# 随机产生abcdefg球员中的3-6个人随机进1-4个球

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

res = []

for k in s1:

if k in s2 and k in s3:

res.append(k)

map函数

map(function, iterable, ...) 函数会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用function 函数,返回包含每次 function 函数返回值的新列表。

# 计算平方数

def square(x) :

return x ** 2

map(square, [1,2,3,4,5])

# 使用 lambda 匿名函数

map(lambda x: x ** 2, [1, 2, 3, 4, 5])

# [1, 4, 9, 16, 25]

# 提供了两个列表,对相同位置的列表数据进行相加

map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])

# [3, 7, 11, 15, 19]

reduce函数

reduce(function, iterable) 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

# 求和

reduce(lambda x, y: x+y, [1,2,3,4,5])

# 15

最后

from random import randint, sample

from functools import reduce

# 随机产生abcdefg球员中的3-6个人随机进1-4个球

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

res = reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3]))

print(res)

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子