zoukankan      html  css  js  c++  java
  • 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把结果和序列的下一个元素做累计运算。

  • 相关阅读:
    列表的常用的方法(内建函数)
    关于集合
    scribe、chukwa、kafka、flume日志系统对比
    iptables,lokkit,ebtables,arptables---logrotate
    MTA---smtp(25,postfix,sendmail),Pop3(110,Devocot), MUA(foxmail) IMAP(server,client rsync)
    DNS named. bind linux (ACL/View)---dnsmasq-with docker,hosts in docker.
    javascript closure
    Typed Arrays in javascripts
    OpenPGP协议的一个JavaScript实现:OpenPGP.js
    公有云安全工具
  • 原文地址:https://www.cnblogs.com/daacheng/p/7912280.html
Copyright © 2011-2022 走看看