如果我有這樣的代碼:
for i in range(3):
print("Hello")
有沒有辦法讓它用for回圈永遠列印?
uj5u.com熱心網友回復:
如果您的 for 回圈從永遠運行的生成器中獲取資料,請確保:
def infinite():
while True:
yield
for __ in infinite():
print("Hello")
你問它是否可以作為單線完成。不是這樣,但有一些技巧(并且不會通過從其他地方匯入它而作弊itertools):
for __ in iter(int, 1):
print("Hello")
這是有效的,因為int()它將0無休止地回傳,永遠不會達到 的哨兵值1。我仍然覺得它有點作弊,你只會這樣做是為了表明它可以完成for-while True:如果你真的需要它,顯然這是要走的路。
uj5u.com熱心網友回復:
你可以使用類似的東西itertools.count:
from itertools import count
for i in count():
print(i)
uj5u.com熱心網友回復:
有什么理由需要 for 回圈嗎?
你可以只使用一個while回圈,
while True:
print('hello')
要停止它,請按鍵盤上的Ctrl c。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/359201.html
上一篇:如何避免for回圈并在此代碼中使用替代方法(python和postgressql)?。下面是我的代碼
下一篇:從for回圈輸出創建多個箱線圖
