【问题标题】:converting to list comprehension转换为列表理解
【发布时间】:2014-05-02 12:35:22
【问题描述】:

我有这个代码:

result = []
for x in [10, 20, 30]:
    for y in [2, 3, 4]:
        if y > 0:
            result.append(x ** y)

结果

[100, 1000, 10000, 400, 8000, 160000, 900, 27000, 810000]

我正在尝试将其转换为列表理解但没有运气(python 中的新功能)

这是我的尝试:

print [ x ** y if y > 0 for x in [10, 20, 30] for y in [2, 3, 4]]

但是声明有问题,任何帮助都将是最合适的。

错误:

  File "<stdin>", line 1
    print [ x ** y if y > 0 for x in [10, 20, 30] for y in [2, 3, 4]]
                              ^
SyntaxError: invalid syntax

【问题讨论】:

    标签: python list list-comprehension


    【解决方案1】:

    过滤条件必须在最后,像这样

    print [x ** y for x in [10, 20, 30] for y in [2, 3, 4] if y > 0]
    

    因为grammar for list comprehension 是这样定义的

    list_display        ::=  "[" [expression_list | list_comprehension] "]"
    list_comprehension  ::=  expression list_for
    list_for            ::=  "for" target_list "in" old_expression_list [list_iter]
    list_iter           ::=  list_for | list_if
    list_if             ::=  "if" old_expression [list_iter]
    

    所以只有表达式可以出现在for..in 之前,而if 语句只能出现在之后。

    在你的情况下,expression 满足 x ** y 然后 list_for 满足 for x in [10, 20, 30] 然后另一个 list_for 满足 for x in [10, 20, 30] 最后 list_if 满足 @987654334 @。它的形式是

    [ expression list_for list_for list_if ]
    

    顺便说一句,你可以对itertools.product做同样的事情,就像这样

    from itertools import product
    print [num**power for num,power in product([10, 20, 30], [2, 3, 4]) if power > 0]
    

    【讨论】:

    • 您可能会展示如何在itertools 版本中合并过滤器(可能在product 的第二个参数上使用itertools.ifilter)。
    【解决方案2】:

    list comprehension 末尾需要 if 语句

    print [ x ** y for x in [10, 20, 30] for y in [2, 3, 4] if y > 0]
    

    【讨论】:

      【解决方案3】:

      记住这个语法以便理解。 '{}' 用于 dict 理解

      [ expression for target1 in iterable1 if condition1
      for target2 in iterable2 if condition2 ...
      for targetN in iterableN if conditionN ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        相关资源
        最近更新 更多