【问题标题】:Dictionary Comprehension example字典理解示例
【发布时间】:2016-05-18 09:53:17
【问题描述】:

我有一个集合,其中包含 n 组素数(3):

>>> sets
{frozenset({3, 13, 23}), frozenset({17, 2, 13}), 
frozenset({19, 2, 3}), frozenset({3, 29, 23}), frozenset({17, 11, 23}),
frozenset({17, 2, 19}), frozenset({11, 17, 3}), frozenset({17, 5, 7})}

我想创建具有值的字典:素数三元组和键:三个素数的乘积。

这是我的尝试:

lists = [list(i) for i in sets]
products = [reduce(lambda x,y:x*y,i) for i in lists]
dictir = {x:y for x in products for y in sets}

但是 dictir 给了我不正确的结果:

{897: frozenset({17, 5, 7}), 114: frozenset({17, 5, 7}), 595: frozenset({17, 5, 7}), 561: frozenset({17, 5, 7}), 646: frozenset({17, 5, 7}), 2001: frozenset({17, 5, 7}), 442: frozenset({17, 5, 7}), 4301: frozenset({17, 5, 7})}

你能帮我纠正一下吗?

【问题讨论】:

    标签: python dictionary set dictionary-comprehension


    【解决方案1】:

    您进行双重迭代并有效地创建listsproducts 的笛卡尔积。

    要在多个序列上逐元素迭代,只需使用zip

    dictir = {x: y for x, y in zip(products, sets)} 
    

    当然你可以去掉所有的中间变量,做简单的单行:

    sets = {frozenset({3, 13, 23}), frozenset({17, 2, 13}),
            frozenset({19, 2, 3}), frozenset({3, 29, 23}), frozenset({17, 11, 23}),
            frozenset({17, 2, 19}), frozenset({11, 17, 3}), frozenset({17, 5, 7})}
    dictir = {reduce(lambda x, y: x * y, s): s for s in sets}
    

    【讨论】:

      【解决方案2】:

      您可以使用zip(),但另一种更有效的方法是:

      import operator
      tuples = ((reduce(operator.mul, i), i) for i in sets)
      dictir = dict(tuples)
      
      # Or as a 1 liner
      dictir = {reduce(operator.mul, i): i for i in sets}
      

      【讨论】:

      • 它给了我“SyntaxError: invalid syntax”
      • @YNWA1992 已修复并经过测试。
      【解决方案3】:

      我认为,您可以简单地使用它:

      import operator
      dictir = {reduce(operator.mul,numbers):numbers for value in sets}
      

      【讨论】:

        猜你喜欢
        • 2013-07-05
        • 1970-01-01
        • 2021-07-24
        • 2016-09-03
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        相关资源
        最近更新 更多