美文网首页
多个dict公共key

多个dict公共key

作者: DamageDurex | 来源:发表于2017-10-01 23:39 被阅读0次

    案例:找到多个dict的的公共key

    如 {'a':1,'b':2,'c':3}, {'x':1,'b':33,'z':100} 则查找出b

    from random import randint, sample
    # 生成随机的字典
    c1 = {key: randint(1,3) for key in sample('abcdefg',ranint(3,6))}
    c2 = {key: randint(1,3) for key in sample('abcdefg',ranint(3,6))}
    c3 = {key: randint(1,3) for key in sample('abcdefg',ranint(3,6))}
    # 对于固定数量可以使用集合的并集操作
    c1.viewkeys() & c2.viewkeys() & c3.viewkeys()
    
    # 对于n个 使用map reduce操作
    reduce(lambda old, new: old & new, map(dict.viewkeys, [c1,c2,c3]))
    

    相关文章

      网友评论

          本文标题:多个dict公共key

          本文链接:https://www.haomeiwen.com/subject/hbqzextx.html