足球聯(lián)賽,對(duì)每一輪進(jìn)球球員進(jìn)行統(tǒng)計(jì),計(jì)算每一輪都有進(jìn)球的球員。
from functools import reduce
from random import randint, sample
import timeit
sample("abcdefg", randint(3, 6)) # 隨機(jī)取樣三到六個(gè)
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))}
def get_for():
res = []
for key1 in s1:
for key2 in s2:
if key1 == key2:
res.append(key1)
return res
def get_common():
return s1.keys() & s2.keys()
if __name__ == "__main__":
print(s1, s2, s3)
# 以下兩種方法功能基本相同
print(get_for())
print(s1.keys() & s2.keys())
print(timeit.timeit(get_for))
print(timeit.timeit(get_common)) # 此方法時(shí)間明顯低與迭代。
# 多個(gè)字典的公共鍵
print(reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3])))