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把结果和序列的下一个元素做累计运算。

  • 相关阅读:
    我想操作的是利用SqlDataAdapter的几个Command属性(InsertCommand,UpdateCommand,DeleteCommand)来更新数据库
    有两个数据库A和B,数据库A中有表a,如何把表a映射到数据库B中,sql 2005
    代码生成器
    IWorkSpace接口介绍
    空间数据库介绍
    IGeoFeatureLayer
    IFeatureLayer
    Python ML环境搭建与学习资料推荐
    Python ML环境搭建与学习资料推荐
    TypeError: Can not convert a float32 into a Tensor or Operation.
  • 原文地址:https://www.cnblogs.com/daacheng/p/7912280.html
Copyright © 2011-2022 走看看