問題描述
我可能以錯誤的方式處理這個問題,但我想知道如何在 python 中處理這個問題.
I am probably going about this in the wrong manner, but I was wondering how to handle this in python.
首先是一些c代碼:
int i;
for(i=0;i<100;i++){
if(i == 50)
i = i + 10;
printf("%i
", i);
}
好吧,所以我們永遠不會看到 50 年代...
Ok so we never see the 50's...
我的問題是,我怎樣才能在 python 中做類似的事情?例如:
My question is, how can I do something similar in python? For instance:
for line in cdata.split('
'):
if exp.match(line):
#increment the position of the iterator by 5?
pass
print line
由于我在 python 方面的經驗有限,我只有一個解決方案,引入一個計數器和另一個 if 語句.在 exp.match(line) 為真后中斷循環直到計數器達到 5.
With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true.
必須有更好的方法來做到這一點,希望不涉及導入另一個模塊.
There has got to be a better way to do this, hopefully one that does not involve importing another module.
提前致謝!
推薦答案
Python中有一個很棒的包,叫做itertools
.
There is a fantastic package in Python called itertools
.
但在我開始之前,先解釋一下迭代協議是如何在 Python 中實現的.當你想在你的容器上提供迭代時,你指定 __iter__()
類方法,提供 迭代器類型."理解 Python 的 'for' 語句" 是一篇很好的文章,介紹了 for-in
語句實際上在 Python 中工作,并提供了關于迭代器類型如何工作的很好的概述.
But before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the __iter__()
class method that provides an iterator type. "Understanding Python's 'for' statement" is a nice article covering how the for-in
statement actually works in Python and provides a nice overview on how the iterator types work.
看看以下內容:
>>> sequence = [1, 2, 3, 4, 5]
>>> iterator = sequence.__iter__()
>>> iterator.next()
1
>>> iterator.next()
2
>>> for number in iterator:
print number
3
4
5
現在回到 itertools
.該包包含用于各種迭代目的的函數.如果您需要進行特殊排序,這是首先要研究的地方.
Now back to itertools
. The package contains functions for various iteration purposes. If you ever need to do special sequencing, this is the first place to look into.
在底部,您可以找到包含 的 Recipes 部分使用現有的 itertools 作為構建塊創建擴展工具集的秘訣.
At the bottom you can find the Recipes section that contain recipes for creating an extended toolset using the existing itertools as building blocks.
還有一個有趣的功能可以滿足您的需求:
And there's an interesting function that does exactly what you need:
def consume(iterator, n):
'''Advance the iterator n-steps ahead. If n is none, consume entirely.'''
collections.deque(itertools.islice(iterator, n), maxlen=0)
這是一個關于其工??作原理的快速、易讀的示例(Python 2.5):
Here's a quick, readable, example on how it works (Python 2.5):
>>> import itertools, collections
>>> def consume(iterator, n):
collections.deque(itertools.islice(iterator, n))
>>> iterator = range(1, 16).__iter__()
>>> for number in iterator:
if (number == 5):
# Disregard 6, 7, 8, 9 (5 doesn't get printed just as well)
consume(iterator, 4)
else:
print number
1
2
3
4
10
11
12
13
14
15
這篇關于python在循環內任意遞增迭代器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!