[英]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.