gpt4 book ai didi

python在循环内任意递增迭代器

转载 作者:IT老高 更新时间:2023-10-28 20:34:30 24 4
gpt4 key购买 nike

我可能以错误的方式处理这个问题,但我想知道如何在 python 中处理这个问题。

首先是一些c代码:

int i;

for(i=0;i<100;i++){
if(i == 50)
i = i + 10;
printf("%i\n", i);
}

好吧,所以我们永远不会看到 50 年代...

我的问题是,我怎样才能在 python 中做类似的事情?例如:

for line in cdata.split('\n'):
if exp.match(line):
#increment the position of the iterator by 5?
pass
print line

由于我在 python 方面的经验有限,我只有一个解决方案,引入一个计数器和另一个 if 语句。在 exp.match(line) 为真后中断循环直到计数器达到 5。

必须有更好的方法来做到这一点,希望不涉及导入另一个模块。

提前致谢!

最佳答案

Python 中有一个很棒的包,叫做 itertools .

但在我开始之前,先解释一下迭代协议(protocol)是如何在 Python 中实现的。当你想在你的容器上提供迭代时,你指定 __iter__()提供 iterator type 的类方法. "Understanding Python's 'for' statement"是一篇很好的文章,介绍了 for-in 语句在 Python 中的实际工作方式,并很好地概述了迭代器类型的工作方式。

看看以下内容:

>>> 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。该包包含用于各种迭代目的的函数。如果您需要进行特殊排序,这是首先要研究的地方。

在底部您可以找到 Recipes部分包含使用现有 itertools 作为构建 block 创建扩展工具集的方法

还有一个有趣的功能可以满足您的需求:

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):

>>> 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在循环内任意递增迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1474646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com