• 【Python基础教程】快速找到多个字典中的公共键(key)的方法


    方法一:for in循环

    from random import randint, sample
    
    a1 = {k: randint(1, 4) for k in 'abcdefg'}
    a2 = {k: randint(1, 4) for k in 'abc123456789'}
    a3 = {k: randint(1, 4) for k in 'abcinubububu'}
    a4 = {k: randint(1, 4) for k in 'abc89898989'}
    r = []
    
    for x in a1:
        if x in a2 and x in a3 and x in a4:
            r.append(x)
    print(r)
    randint(1, 4)  # 从1~4间随机取一个数
    

    方法二:利用集合的交集操作

    '''
    学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025
    寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
    '''
    from random import randint, sample
    
    a1 = {k: randint(1, 4) for k in 'abcdefg'}
    a2 = {k: randint(1, 4) for k in 'abcdefg'}
    a3 = {k: randint(1, 4) for k in 'abcdefg'}
    a4 = {k: randint(1, 4) for k in 'abcdefg'}
    
    a = a1.keys() & a2.keys() & a3.keys() & a4.keys()
    print(a)
    

    a1.keys():得到a1字典的key,一set格式;
    a1.keys() & a2.keys() & a3.keys() & a4.keys():取4个集合的公共元素;
    a为一个集合(set)

    方法三:使用map即reduce(用于求n个字典的公共key)

    from random import randint, sample
    from functools import reduce
    
    a1 = {k: randint(1, 4) for k in 'abcdefg'}
    a2 = {k: randint(1, 4) for k in 'abcdefg'}
    a3 = {k: randint(1, 4) for k in 'abcdefg'}
    a4 = {k: randint(1, 4) for k in 'abcdefg'}
    
    b1 = map(dict.keys, [a1, a2, a3, a4])
    b2 = reduce(lambda a ,b: a & b, b1)
    
    print(b2)
    
    b1 = map(dict.keys, [a1, a2, a3, a4])  #以集合形式取每个字典的keys;
    
  • 相关阅读:
    Python36和Python27共存的方法
    普通用户启动redis
    NetHogs 实时检测网络流量 转
    Linux命令nohup+screen 转
    变更Linux下的Java版本 alternatives
    centos7下使用yum安装mysql
    CentOS6.6系统中安装配置Samba的教程
    Linux服务器中木马(肉鸡)手工清除方法(转)
    linux杀毒软件clamav安装与使用
    msys git 安装配置、git命令行使用
  • 原文地址:https://www.cnblogs.com/djdjdj123/p/15374157.html
Copyright © 2020-2023  润新知