image.png
sample(seq, n)
從序列seq中選擇n個隨機且不相同的元素眼俊;
一般的方法意狠,但是效率不高
from random import randint, sample
# 隨機產(chǎn)生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)
解決方法
image.png
map函數(shù)
map(function, iterable, ...)
函數(shù)會根據(jù)提供的函數(shù)對指定序列做映射。
第一個參數(shù)function
以參數(shù)序列中的每一個元素調(diào)用function
函數(shù)疮胖,返回包含每次function
函數(shù)返回值的新列表环戈。
# 計算平方數(shù)
def square(x) :
return x ** 2
map(square, [1,2,3,4,5])
# 使用 lambda 匿名函數(shù)
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
# [1, 4, 9, 16, 25]
# 提供了兩個列表,對相同位置的列表數(shù)據(jù)進行相加
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
# [3, 7, 11, 15, 19]
reduce函數(shù)
reduce(function, iterable)
函數(shù)會對參數(shù)序列中元素進行累積澎灸。
函數(shù)將一個數(shù)據(jù)集合(鏈表院塞,元組等)中的所有數(shù)據(jù)進行下列操作:用傳給reduce
中的函數(shù)function
(有兩個參數(shù))先對集合中的第 1、2 個元素進行操作性昭,得到的結(jié)果再與第三個數(shù)據(jù)用function
函數(shù)運算拦止,最后得到一個結(jié)果。
# 求和
reduce(lambda x, y: x+y, [1,2,3,4,5])
# 15
最后
from random import randint, sample
from functools import reduce
# 隨機產(chǎn)生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)