在Python中,我通常通過循環範圍僅僅通過如何跳過幾次迭代的for循環
但現在我想跳過循環幾步之遙。更具體地說,我想要像continue(10)
這樣它會跳過整個循環,並增加計數器10.如果我在C中使用for循環,我只能總結10 i
,但在Python中並不真正工作。
在Python中,我通常通過循環範圍僅僅通過如何跳過幾次迭代的for循環
但現在我想跳過循環幾步之遙。更具體地說,我想要像continue(10)
這樣它會跳過整個循環,並增加計數器10.如果我在C中使用for循環,我只能總結10 i
,但在Python中並不真正工作。
您不能更改for
循環的目標列表(本例中爲i
)。使用while
循環,而不是:
while i < 10:
i += 1
if i == 2:
i += 3
另外,使用迭代和增量是:
from itertools import islice
numbers = iter(range(10))
for i in numbers:
if i == 2:
next(islice(numbers, 3, 3), None) # consume 3
通過分配的iter()
結果到一個局部變量,我們可以利用先進的循環內的循環順序標準迭代工具(next()
,或這裏,itertools
消耗配方的縮短版本)。 for
通常在迭代器上循環時調用iter()
。
最好的方法是爲迭代器指定一個名稱 - 通常有一個迭代器,而不是迭代器(差別是迭代器 - 例如列表 - 每次迭代時都從頭開始)。在這種情況下,只要使用the iter()
built-in function:
numbers = iter(range(100))
然後你可以提前使用它的名字在循環中。最好的方法是使用the itertools
consume()
recipe - 因爲它速度很快(它使用itertools
函數來確保迭代發生在低級代碼中,使得消耗值的過程非常快,並避免通過存儲消耗的值來消耗內存):
from itertools import islice
import collections
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
通過這樣做,你可以這樣做:
numbers = iter(range(100))
for i in numbers:
...
if some_check(i):
consume(numbers, 3) # Skip 3 ahead.
請注意,即使在Python 3中,您也可以*調用'range()'上的iter()來使其工作。 Python 3'range()'對象是一個序列(可迭代的),而不是迭代器。 –
@MartijnPieters令人難以置信的好點。編輯。我遍歷範圍很少,我忘記了這種情況。 –
好的答案+1 –
爲什麼不直接設置爲跳過,直到價值?像:
skip_until = 0
for i in range(100):
if i < skip_until:
continue
if SOME_CONDITION:
skip_until = i + 10
DO_SOMETHING()
其中SOME_CONDITION是什麼使你跳過和DO_SOMETHING()是實際循環的內容?
+1,'continue'是最不復雜的方式。 – 2rs2ts
值得注意的是,這需要在Python中執行循環,並且每次都指定名稱 - 儘管在大多數情況下這不太可能是個問題,但從這個意義上講效率要低得多。 –
是的,但考慮到簡單的問題,我想他想要一個簡單的答案;如果循環/跳過很小,用迭代器搞亂看起來好像過度。 –
for i in range(0, 100, 10):
print(i)
將打印0,10,20 ...
嗨,雖然這跳過了前10個值,但我認爲提問者更感興趣的是知道如何在循環**中**跳到任意值。查看頂部答案的例子。 – seth
你絕對不需要python 3.3。 –
我想這可能是這樣,while循環,也只是很悲傷。無論如何, –
結束了while循環!萬分感謝! –
@AlexS如果您正在迭代數字,那很好 - 如果您使用這些數字作爲列表或其他的索引,請不要這樣做。按索引迭代在各方面都很糟糕。 –