簡體   English   中英

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

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

Python語法規范來看,只允許以下原子表達式:

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語句。 您可以使用的唯一關鍵字是forfor循環。

解決方案

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM