- 第一种
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'}
- 第二种
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'}