1 ''' 2 快速找到多个字典的公共键(key) 3 ''' 4 from functools import reduce 5 from random import randint,sample 6 #随机取样 在'abcdefg'七个字母中随机取3个 7 s1 = sample('abcdefg',3) 8 print(s1) 9 #随机取样 在'abcdefg'七个字母中随机取3-7个 10 s2 = sample('abcdefg',randint(3,7)) 11 dict1 = {x:randint(1,4) for x in sample('abcdefg',randint(3,7))} 12 dict2 = {x:randint(1,4) for x in sample('abcdefg',randint(3,7))} 13 dict3 = {x:randint(1,4) for x in sample('abcdefg',randint(3,7))} 14 print(dict1) 15 print(dict2) 16 print(dict3) 17 res=[] 18 #遍历出公共键 19 for x in dict1: 20 if x in dict2 and x in dict3: 21 res.append(x) 22 23 print(res) 24 25 #使用集合找出公共键 dict.keys为字典的K 26 print(dict1.keys()) 27 28 res1 = dict1.keys() & dict2.keys() & dict3.keys() 29 print(res1) 30 31 32 #使用map与reduce计算N条集合的公共键 33 dictmap = map(dict.keys,[dict1,dict2,dict3]) 34 print(list(dictmap)) 35 res2 = reduce(lambda x,y : x & y ,map(dict.keys,[dict1,dict2,dict3])) 36 print(res2)