简体   繁体   English

在列表理解中使用“while”循环

[英]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: range只会做:

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

A while loop is not possible inside of a list comprehension. while列表推导式中不可能有while循环。 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.不,您不能在列表理解中使用while

From the grammar specification of Python , only the following atomic expressions are allowed:Python语法规范来看,只允许以下原子表达式:

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的表达式 - testlist_comp在 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.任何地方都不允许有一个while语句。 The only keywords you are allowed to use is a for , for a for loop.您可以使用的唯一关键字是forfor循环。

Solution解决方案

Use a for loop, or take advantage of itertools .使用for循环,或利用itertools

There isn't any syntax for this, but you can use itertools.对此没有任何语法,但您可以使用 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.) (虽然这不是 Pythonic。应该首选生成器解决方案或显式解决方案。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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