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

for i in range(some_number):
    # do something

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


当前回答

我们有一些乐趣与以下,有趣的分享:

class RepeatFunction:
    def __init__(self,n=1): self.n = n
    def __call__(self,Func):
        for i in xrange(self.n):
            Func()
        return Func


#----usage
k = 0

@RepeatFunction(7)                       #decorator for repeating function
def Job():
    global k
    print k
    k += 1

print '---------'
Job()

结果:

0
1
2
3
4
5
6
---------
7

其他回答

也许答案取决于你在使用迭代器时遇到了什么问题? 可能会使用

i = 100
while i:
    print i
    i-=1

or

def loop(N, doSomething):
    if not N:
        return
    print doSomething(N)
    loop(N-1, doSomething)

loop(100, lambda a:a)

但坦率地说,我认为使用这种方法没有任何意义

如果do_something是一个简单的函数或者可以封装在一个简单的函数中,一个简单的map()可以do_something range(some_number)次:

# Py2 version - map is eager, so it can be used alone
map(do_something, xrange(some_number))

# Py3 version - map is lazy, so it must be consumed to do the work at all;
# wrapping in list() would be equivalent to Py2, but if you don't use the return
# value, it's wastefully creating a temporary, possibly huge, list of junk.
# collections.deque with maxlen 0 can efficiently run a generator to exhaustion without
# storing any of the results; the itertools consume recipe uses it for that purpose.
from collections import deque

deque(map(do_something, range(some_number)), 0)

如果你想将参数传递给do_something,你可能还会发现itertools repeatfunc recipe读起来很好:

通过相同的论点:

from collections import deque
from itertools import repeat, starmap

args = (..., my args here, ...)

# Same as Py3 map above, you must consume starmap (it's a lazy generator, even on Py2)
deque(starmap(do_something, repeat(args, some_number)), 0)

传递不同的参数:

argses = [(1, 2), (3, 4), ...]

deque(starmap(do_something, argses), 0)

这里有一个随机的想法,利用(滥用?)数据模型(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

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

你可能正在寻找

for _ in itertools.repeat(None, times): ...

这是Python中迭代次数最快的方法。

每个人建议你使用_并不是说_经常被用作一个gettext函数的快捷方式,所以如果你想让你的软件在多种语言中可用,那么你最好避免将它用于其他目的。

import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')