在列表理解中使用while循环

cas*_*y11 5 python list-comprehension list

说我有一个功能:

x=[]
i=5
while i<=20:
     x.append(i)
     i=i+10
return x
Run Code Online (Sandbox Code Playgroud)

无论如何有这样将其转换为列表理解吗?

newList = [i=05 while i<=20 i=i+10]
Run Code Online (Sandbox Code Playgroud)

我收到语法错误

Aks*_*jan 11

不,您不能while在列表理解中使用。

Python语法规范来看,只允许以下原子表达式:

atom: ('(' [yield_expr|testlist_comp] ')' |    '[' [testlist_comp] ']' |    '{' [dictorsetmaker] '}' |    NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
Run Code Online (Sandbox Code Playgroud)

对应于列表推导式的表达式 -testlist_comp在 Python 3 中如下所示:

testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
Run Code Online (Sandbox Code Playgroud)

在这里,唯一允许的语句是

test: or_test ['if' or_test 'else' test] | lambdef
star_expr: '*' expr
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
Run Code Online (Sandbox Code Playgroud)

在哪里

comp_if: 'if' test_nocond [comp_iter]
comp_iter: comp_for | comp_if
Run Code Online (Sandbox Code Playgroud)

没有一个while允许任何地方的语句。您可以使用的唯一关键字是 a for, for a for循环。

解决方案

使用for循环,或利用itertools.


Fra*_*uzo 5

您不需要为此的列表理解,范围就可以了:

list(range(5, 21, 10)) # [5, 15]
Run Code Online (Sandbox Code Playgroud)

在列表理解内不可能进行while循环,而是可以执行以下操作:

def your_while_generator():
    i = 5
    while i <= 20:
        yield i
        i += 10

[i for i in your_while_generator()]
Run Code Online (Sandbox Code Playgroud)