zoukankan      html  css  js  c++  java
  • python数据结构-如何快速找到多个字典中的公共键

    如何快速找到多个字典中的公共键

    问题举例

    统计每轮都进球的球员:

    第1轮{‘tom’:1, 'meixi':2}

    第2轮{‘coco’:3, 'meixi':4, 'marton':2}

    第3轮{'coco':2, 'meixi':1, 'david':1}

    for循环、列表解析和set交集

    from random import randint, sample
    d1 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))}
    d2 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))}
    d3 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))}
    print(d1, d2, d3)
    
    print("
    (1)for loop")
    res1 = []
    for key in d1:
        if key in d2 and key in d3:
            res1.append(key)
    print(res1)
    
    print("
    (2)list comprehension")
    res = [k for k in d1 if k in d2 and k in d3]
    print(res)
    
    print("
    (3)set intersection")
    s1 = d1.keys()
    s2 = d2.keys()
    s3 = d3.keys()
    res3 = s1 & s2 & s3
    print(res3)

    分析:在实际场景中我们并不知道有几轮,我们需要更通用的一种方法

    我们把字典放在列表中,这里仅以三个字典为例,当然列表中可以放n个字典

    通用方法(两种)

    from random import randint, sample
    from functools import reduce
    d1 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))}
    d2 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))}
    d3 = {k: randint(1, 5) for k in sample('abcdefg', randint(3, 6))}
    print(d1, d2, d3)
    
    d_list = [d1, d2, d3]
    print("
    solution1:")
    res1 = [k for k in d_list[0] if all(map(lambda d: k in d, d_list[1:]))]
    print(res1)
    
    print("
    solution2:")
    res2 = reduce(lambda a, b: a & b, map(dict.keys, d_list))
    print(res2)

    参考资料:python3实用编程技巧进阶

  • 相关阅读:
    反转字符串
    数组
    复杂度分析(二)
    复杂度分析(一)
    业务应该这么写--特性
    5种方法快速启动一个应用程序
    业务应该这么写--表达式树
    业务应该这么写--泛型
    业务应该这么写--异常处理
    关于关系型数据库外键,要减轻数据库压力的一些说法
  • 原文地址:https://www.cnblogs.com/marton/p/10745513.html
Copyright © 2011-2022 走看看