[英]how to use iterator in while loop statement in python
是否可以在 Python 的 while 循環中使用生成器或迭代器? 例如,類似於:
i = iter(range(10))
while next(i):
# your code
這樣做的目的是將迭代構建到 while 循環語句中,使其類似於 for 循環,不同之處在於您現在可以在 while 語句中添加額外的邏輯:
i = iter(range(10))
while next(i) and {some other logic}:
# your code
然后它成為一個很好的 for 循環/while 循環混合。
有誰知道如何做到這一點?
在 Python < 3.8 中,您可以使用itertools.takewhile
:
from itertools import takewhile
i = iter(range(10))
for x in takewhile({some logic}, i):
# do stuff
這里的“一些邏輯”將是一個 1-arg 可調用的接收next(i)
產生的任何內容:
for x in takewhile(lambda e: 5 > e, i):
print(x)
0
1
2
3
4
在 Python >= 3.8 中,您可以使用賦值表達式執行以下操作:
i = iter(range(10))
while (x := next(i, None)) is not None and x < 5:
print(x)
while next(i):
有兩個問題while next(i):
for
循環不同, while
循環不會捕獲在沒有next
值時引發的StopIteration
異常; 在這種情況下,您可以使用next(i, None)
返回“falsey”值,但是只要迭代器返回實際的 falsey 值, while
循環也會停止next
返回的值將被消耗並且不再在循環體中可用。 (在 Python 3.8+ 中,這可以通過賦值表達式解決,請參閱其他答案。) 相反,您可以將for
循環與itertools.takewhile
,從可迭代對象或任何其他條件測試當前元素。 這將循環直到迭代耗盡,或者條件評估為假。
from itertools import takewhile
i = iter(range(10))
r = 0
for x in takewhile(lambda x: r < 10, i):
print("using", x)
r += x
print("result", r)
輸出:
using 0
...
using 4
result 10
您只需要安排您的迭代器在到期時返回一個類似 false 的值。 例如,如果我們反轉range
以使其倒計時為 0:
>>> i = iter(range(5, -1, -1))
>>> while val := next(i):
... print('doing something here with value', val)
...
這將導致:
doing something here with value 5
doing something here with value 4
doing something here with value 3
doing something here with value 2
doing something here with value 1
a = iter(range(10))
try:
next(a)
while True:
print(next(a))
except StopIteration:
print("Stop iteration")
你可以做
a = iter(range(10))
try:
a.next()
while True and {True or False logic}:
print("Bonjour")
a.next()
except StopIteration:
print("a.next() Stop iteration")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.