简体   繁体   中英

Using 'while' loops in a list comprehension

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.

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()]

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 .

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM