簡體   English   中英

重新啟動循環遍歷列表python3

[英]restarting for cycle iterating over list python3

[python] 3.6
您好,我試圖用for循環遍歷列表,每當條件確定時,我都必須重新啟動循環。 在CI中可以做到:
for(i = 0; i < 10; i++){ if(list[i] == something) i = 0; }

在這里,我試圖這樣做:

for x in listPrimes:
    if((num % x) == 0):
        num /= x # divide by the prime
        factorials.append(x)
        x = 2 # reset to the first prime in the list?

不能正常工作。 將for重置為列表的特定迭代的方式有哪些? 我是否必須以其他方式進行?
謝謝你的時間

您可以只使用while循環:

i = 0
while i < 10:
    print("do something", i)
    if random.random() < 0.2:
        print("reset")
        i = -1
    i += 1

針對您的示例:

i = 0
while i < len(listPrimes):
    x = listPrimes[i]
    if num % x == 0:
        num /= x
        factorials.append(x)
        i = -1
    i += 1

您可以像使用C代碼一樣使用while循環。

while i < 10: if list[i] == something: i = 0 i += 1

使用itertools.takewhile util

這是一個人為的示例:

import itertools

li = [1,2,3,4,5]
for i in range(1, 6):
        print(list(itertools.takewhile(lambda x: x!=i, li)))
        print("new cycle")

輸出:

[]
new cycle
[1]
new cycle
[1, 2]
new cycle
[1, 2, 3]
new cycle
[1, 2, 3, 4]
new cycle

while循環是最優雅的解決方案。 為了完整起見,您可以將列表包裝到自定義生成器中,並讓此新的可迭代接收信號重置循環。

import time

def resetable_generator(li):
    while True:
        for item in li:
            reset = yield item
            if reset:
                break
        else:
            raise StopIteration


x = range(10)
sum = 0
r = resetable_generator(x)
for item in r:
    time.sleep(1)
    sum += item
    if item == 6:
        sum += r.send(True)
    print(sum)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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