转换为列表理解

jho*_*nny 3 python list-comprehension list

我有这个代码:

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

结果

[100, 1000, 10000, 400, 8000, 160000, 900, 27000, 810000]
Run Code Online (Sandbox Code Playgroud)

我试图将它转换为列表理解而没有运气(python中的新功能)

这是我的尝试:

print [ x ** y if y > 0 for x in [10, 20, 30] for y in [2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)

但是声明中存在问题,任何帮助都将被最多拨款.

错误:

  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
Run Code Online (Sandbox Code Playgroud)

the*_*eye 7

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

print [x ** y for x in [10, 20, 30] for y in [2, 3, 4] if y > 0]
Run Code Online (Sandbox Code Playgroud)

因为列表理解语法是这样定义的

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]
Run Code Online (Sandbox Code Playgroud)

所以只有表达式才会出现,for..inif声明才能在此之后出现.

在你的情况下,expression满足x ** y然后list_for满足for x in [10, 20, 30],然后另一个list_for满意for x in [10, 20, 30],最后list_if满意if y > 0.它的形式

[ expression list_for list_for list_if ]
Run Code Online (Sandbox Code Playgroud)

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

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


Ffi*_*ydd 6

您需要在列表推导结束时使用if语句

print [ x ** y for x in [10, 20, 30] for y in [2, 3, 4] if y > 0]
Run Code Online (Sandbox Code Playgroud)