zoukankan      html  css  js  c++  java
  • 快速找到多个字典的公共键(key)

     1 '''
     2 快速找到多个字典的公共键(key)
     3 '''
     4 from functools import reduce
     5 from random import randint,sample
     6 #随机取样 在'abcdefg'七个字母中随机取3个
     7 s1 = sample('abcdefg',3)
     8 print(s1)
     9 #随机取样 在'abcdefg'七个字母中随机取3-7个
    10 s2 = sample('abcdefg',randint(3,7))
    11 dict1 = {x:randint(1,4) for x in sample('abcdefg',randint(3,7))}
    12 dict2 = {x:randint(1,4) for x in sample('abcdefg',randint(3,7))}
    13 dict3 = {x:randint(1,4) for x in sample('abcdefg',randint(3,7))}
    14 print(dict1)
    15 print(dict2)
    16 print(dict3)
    17 res=[]
    18 #遍历出公共键
    19 for x in dict1:
    20     if x in dict2 and x in dict3:
    21         res.append(x)
    22 
    23 print(res)
    24 
    25 #使用集合找出公共键  dict.keys为字典的K
    26 print(dict1.keys())
    27 
    28 res1 = dict1.keys() & dict2.keys() & dict3.keys()
    29 print(res1)
    30 
    31 
    32 #使用map与reduce计算N条集合的公共键
    33 dictmap = map(dict.keys,[dict1,dict2,dict3])
    34 print(list(dictmap))
    35 res2 = reduce(lambda x,y : x & y ,map(dict.keys,[dict1,dict2,dict3]))
    36 print(res2)
  • 相关阅读:
    库函数文件操作
    系统文件操作函数
    time函数
    字符(串)输入输出函数
    select&epoll
    epoll
    select
    Apache 配置虚拟主机三种方式
    Apache VirtualHost配置
    Scrapy中用xpath/css爬取豆瓣电影Top250:解决403HTTP status code is not handled or not allowed
  • 原文地址:https://www.cnblogs.com/tngh/p/10426384.html
Copyright © 2011-2022 走看看