如何在Python中限制循环的迭代?

2024-05-23 17:07:57 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个项目列表,我想遍历其中的前几个:

items = list(range(10)) # I mean this to represent any kind of iterable.
limit = 5

天真的实现

来自其他语言的Python naïf可能会编写这种完全可服务且性能良好(如果是单体的话)的代码:

index = 0
for item in items: # Python's `for` loop is a for-each.
    print(item)    # or whatever function of that item.
    index += 1
    if index == limit:
        break

更惯用的实现

但是Python已经枚举了,它很好地包含了大约一半的代码:

for index, item in enumerate(items):
    print(item)
    if index == limit: # There's gotta be a better way.
        break

所以我们要把额外的代码减半。但总有更好的办法。

我们能估计一下下面的伪代码行为吗?

如果enumerate采用了另一个可选的stop参数(例如,它采用了这样的start参数:enumerate(items, start=1)),我认为这是理想的,但下面的参数不存在(请参见documentation on enumerate here):

# hypothetical code, not implemented:
for _, item in enumerate(items, start=0, stop=limit): # `stop` not implemented
    print(item)

注意,不需要命名index,因为不需要引用它。

有没有一种惯用的方法来写上面的东西?怎样?

第二个问题:为什么不将其内置到枚举中?


Tags: of代码infor参数indexifitems
3条回答

为什么不简单地使用

for item in items[:limit]: # or limit+1, depends
    print(item)    # or whatever function of that item.

这只适用于一些iterable,但是由于您指定了列表,所以它可以工作。

如果你使用集合或听写等,它就不起作用

How can I limit iterations of a loop in Python?

for index, item in enumerate(items):
    print(item)
    if index == limit:
        break

Is there a shorter, idiomatic way to write the above? How?

包括索引

zip在其参数的最短iteable上停止。(与使用最长iterable的zip_longest的行为相反。)

range可以提供一个有限的iterable,我们可以将它与主iterable一起传递给zip。

因此,我们可以将range对象(带有stop参数)传递给zip,并像有限枚举一样使用它。

zip(range(limit), items)

使用Python 3,ziprange返回iterables,它通过管道传输数据,而不是在中间步骤的列表中具体化数据。

for index, item in zip(range(limit), items):
    print(index, item)

要在Python 2中获得相同的行为,只需将xrange替换为range,将itertools.izip替换为zip

from itertools import izip
for index, item in izip(xrange(limit), items):
    print(item)

如果不需要索引,itertools.islice

您可以使用itertools.islice

for item in itertools.islice(items, 0, stop):
    print(item)

它不需要分配给索引。

组合enumerate(islice(items, stop))以获取索引

正如Pablo Ruiz Ruiz所指出的,我们也可以用枚举来组成岛。

for index, item in enumerate(islice(items, limit)):
    print(index, item)

Why isn't this built into enumerate?

下面是用纯Python实现的枚举(可能会进行修改以在注释中获得所需的行为):

def enumerate(collection, start=0):  # could add stop=None
    i = start
    it = iter(collection)
    while 1:                         # could modify to `while i != stop:`
        yield (i, next(it))
        i += 1

对于那些已经使用枚举的人来说,上面的性能会降低,因为它必须检查是否是停止每个迭代的时间。如果没有stop参数,我们可以检查并使用旧的枚举:

_enumerate = enumerate

def enumerate(collection, start=0, stop=None):
    if stop is not None:
        return zip(range(start, stop), collection)
    return _enumerate(collection, start)

这种额外的检查对性能的影响可以忽略不计。

至于为什么枚举没有stop参数,这是最初提出的(参见PEP 279):

This function was originally proposed with optional start and stop arguments. GvR [Guido van Rossum] pointed out that the function call enumerate(seqn, 4, 6) had an alternate, plausible interpretation as a slice that would return the fourth and fifth elements of the sequence. To avoid the ambiguity, the optional arguments were dropped even though it meant losing flexibility as a loop counter. That flexibility was most important for the common case of counting from one, as in:

for linenum, line in enumerate(source,1):  print linenum, line

显然start之所以被保留是因为它非常有价值,而stop之所以被删除是因为它的用例较少,并且导致了对新函数使用的混淆。

避免使用下标符号进行切片

另一个答案是:

Why not simply use

for item in items[:limit]: # or limit+1, depends

这里有几个缺点:

  • 它只适用于接受切片的iterable,因此它更为有限。
  • 如果它们接受切片,通常会在内存中创建一个新的数据结构,而不是在引用数据结构上迭代,因此会浪费内存(所有内置对象在切片时都会进行复制,但是,例如,numpy数组在切片时会生成一个视图)。
  • 不可许可的iterables需要另一种处理方式。如果您切换到一个惰性的计算模型,那么您还必须使用切片来更改代码。

只有在理解限制以及它是生成副本还是视图时,才应使用带下标符号的切片。

结论

我假设现在Python社区知道了枚举的用法,参数的值将超过混淆成本。

在此之前,您可以使用:

for index, element in zip(range(limit), items):
    ...

或者

for index, item in enumerate(islice(items, limit)):
    ...

或者,如果您根本不需要索引:

for element in islice(items, 0, limit):
    ...

避免使用下标符号进行切片,除非您了解这些限制。

你可以用^{}来做这个。它接受startstopstep参数,如果只传递一个参数,则它被视为stop。它将与任何iterable一起工作。

itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop[, step])

演示:

>>> from itertools import islice
>>> items = list(range(10))
>>> limit = 5
>>> for item in islice(items, limit):
    print item,
...
0 1 2 3 4

文档示例:

islice('ABCDEFG', 2) --> A B
islice('ABCDEFG', 2, 4) --> C D
islice('ABCDEFG', 2, None) --> C D E F G
islice('ABCDEFG', 0, None, 2) --> A C E G

相关问题 更多 >