Using 'while' loops in a list comprehension

非 Y 不嫁゛ 提交于 2020-12-08 06:07:49

问题


Say I have a function:

x=[]
i=5
while i<=20:
     x.append(i)
     i=i+10
return x

Is there a way to convert it to a list comprehension like this?

newList = [i=05 while i<=20 i=i+10]

I get a syntax error.


回答1:


You don't need a list comprehension for that. range will just do:

list(range(5, 21, 10)) # [5, 15]

A while loop is not possible inside of a list comprehension. Instead, you could do something like this:

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

[i for i in your_while_generator()]



回答2:


No, you cannot use while in a list comprehension.

From the grammar specification of Python, only the following atomic expressions are allowed:

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

The expression corresponding to a list comprehension - testlist_comp looks like the following in Python 3:

testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

Here, the only statements allowed are

test: or_test ['if' or_test 'else' test] | lambdef
star_expr: '*' expr
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]

where

comp_if: 'if' test_nocond [comp_iter]
comp_iter: comp_for | comp_if

There is not a single while statement allowed anywhere. The only keywords you are allowed to use is a for, for a for loop.

Solution

Use a for loop, or take advantage of itertools.




回答3:


There isn't any syntax for this, but you can use itertools. For example:

In [11]: from itertools import accumulate, repeat, takewhile

In [12]: list(takewhile(lambda x: x <= 20, accumulate(repeat(1), lambda x, _: x + 10)))
Out[12]: [1, 11]

(That's not Pythonic though. The generator solution or explicit solution should be preferred.)



来源:https://stackoverflow.com/questions/42707435/using-while-loops-in-a-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!