可以不带i来做下面的事情吗?

for i in range(some_number):
    # do something

如果你只是想做某件事N次而不需要迭代器。


当前回答

这里有一个随机的想法,利用(滥用?)数据模型(Py3链接)。

class Counter(object):
    def __init__(self, val):
        self.val = val

    def __nonzero__(self):
        self.val -= 1
        return self.val >= 0
    __bool__ = __nonzero__  # Alias to Py3 name to make code work unchanged on Py2 and Py3

x = Counter(5)
while x:
    # Do something
    pass

我想知道在标准库中是否有类似的东西?

其他回答

可以使用_11(或任何数字或其他无效标识符)来防止与gettext发生名称冲突。任何时候你使用下划线+无效标识符,你得到一个可以在for循环中使用的虚拟名称。

#Return first n items of the iterable as a list
list(itertools.islice(iterable, n))

摘自http://docs.python.org/2/library/itertools.html

我大体上同意以上给出的解决方案。即:

在for循环中使用下划线(2行或更多行) 定义一个普通的while计数器(3行或更多行) 用__nonzer__实现声明一个自定义类(更多行)

如果要像#3中那样定义一个对象,我建议实现protocol for with keyword或apply contextlib。

此外,我还提出另一种解决办法。它是一个3行代码,并不是非常优雅,但它使用itertools包,因此可能会感兴趣。

from itertools import (chain, repeat)

times = chain(repeat(True, 2), repeat(False))
while next(times):
    print 'do stuff!'

在这个例子中,2是循环迭代的次数。Chain包装了两个重复迭代器,第一个是有限的,第二个是无限的。记住,这些是真正的迭代器对象,因此它们不需要无限内存。显然,这比解决方案#1要慢得多。除非作为函数的一部分编写,否则可能需要清理times变量。

这里有一个随机的想法,利用(滥用?)数据模型(Py3链接)。

class Counter(object):
    def __init__(self, val):
        self.val = val

    def __nonzero__(self):
        self.val -= 1
        return self.val >= 0
    __bool__ = __nonzero__  # Alias to Py3 name to make code work unchanged on Py2 and Py3

x = Counter(5)
while x:
    # Do something
    pass

我想知道在标准库中是否有类似的东西?

是什么:

while range(some_number):
    #do something