[英]Using 'while' loops in a list comprehension
说我有一个功能:
x=[]
i=5
while i<=20:
x.append(i)
i=i+10
return x
有没有办法将其转换为这样的列表理解?
newList = [i=05 while i<=20 i=i+10]
我收到语法错误。
你不需要列表理解。 range
只会做:
list(range(5, 21, 10)) # [5, 15]
while
列表推导式中不可能有while
循环。 相反,您可以执行以下操作:
def your_while_generator():
i = 5
while i <= 20:
yield i
i += 10
[i for i in your_while_generator()]
不,您不能在列表理解中使用while
。
atom: ('(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictorsetmaker] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
对应于列表testlist_comp
的表达式 - testlist_comp
在 Python 3 中如下所示:
testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
在这里,唯一允许的语句是
test: or_test ['if' or_test 'else' test] | lambdef
star_expr: '*' expr
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
在哪里
comp_if: 'if' test_nocond [comp_iter]
comp_iter: comp_for | comp_if
任何地方都不允许有一个while
语句。 您可以使用的唯一关键字是for
、 for循环。
使用for
循环,或利用itertools
。
对此没有任何语法,但您可以使用 itertools。 例如:
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]
(虽然这不是 Pythonic。应该首选生成器解决方案或显式解决方案。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.