python学习--快速找到多个字典中的公共key

首先先生成几个字典dict。随机生成一个字典,字典的key和value都是随机的。

from random import randint,sample
sample('abcdef',3)  随机取样函数,第二个参数代表取样的个数。

{x:randint(1,4) for x in sample('abcdefg',randint(3,6))}   解释:随机生成一个3-6个元素的dict,集合的值在1-4之间

1.最菜的方法

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 x in s1:               #对字典进行迭代,也就是对字典的key进行迭代,x指的是字典的每一个key。
  if x in s2 and x in s3:
    res.append(x)
  print(res)

2、用集合的交集方式

from functools import reduce

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))}
s1.keys()&s2.keys()&s3.keys()    #字典的keys()方法返回的是一个集合,集合里面包含dict中所有的key

提升:对于n个字典,利用map函数和reduce函数

map(dict.keys,[s1,s2,s3,s4……])   #返回值为 [dict_keys(['c', 'f', 'b']) , dict_keys(['c', 'e', 'd', 'a', 'f'])  ,dict_keys(['b', 'a', 'e'])]

reduce(lambda x,y:x&y,map(dict.keys,[s1,s2,s3]))    ===s1.keys()&s2.keys()&s3.keys() 

map()函数接受两个参数,第一个参数是函数,第二个参数是Iterable,map把传入的函数依次作用到Iterable上的每一个元素,返回一个Iterator。

reduce()函数接受一个函数,一个序列,reduce中的函数接受两个参数x,y。reduce把结果和序列的下一个元素做累计运算。

 

posted @ 2017-11-28 21:48  哒哒哒大大诚  阅读(1005)  评论(0编辑  收藏  举报