zoukankan      html  css  js  c++  java
  • 从多个字典中提取相同的key

    有时有多个字典,需要从中提取出这些字典中共有的key

    #!/usr/bin/env python
    #coding:utf-8
    #@Author:Andy
    
    from random import randint, sample
    # select the same key from different dict
    print("Generate 3 dif dict:")
    
    d1 = {k:randint(1, 10) for k in sample(["小王","小段","小李","小周","小小"],randint(1,5))}
    d2 = {k:randint(1, 10) for k in sample(["小王","小段","小李","小周","小小"],randint(1,5))}
    d3 = {k:randint(1, 10) for k in sample(["小王","小段","小李","小周","小小"],randint(1,5))}
    for _ in (d1, d2, d3):
    	print(_)
    
    print("method 1:")
    res = []
    for _ in d1:
    	if _ in d2 and _ in d3:
    		res.append(_)
    print(res)
    

     

    但是注意,如果出现 :sample larger than population的错误提示:如下图:

    那是因为,randint(x,y)是左右都包含的,如果元素就5个,却用了randin(1,6),就可能超出边界。

  • 相关阅读:
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    National Treasures HDU
    Matrix HDU
    过山车 HDU
    Jimmy’s Assignment HDU
    Card Game Cheater HDU
    Uncle Tom's Inherited Land* HDU
    50 years, 50 colors HDU
  • 原文地址:https://www.cnblogs.com/Andy963/p/6958844.html
Copyright © 2011-2022 走看看