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

for i in range(some_number):
    # do something

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


当前回答

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

其他回答

如果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)

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

import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
#Return first n items of the iterable as a list
list(itertools.islice(iterable, n))

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

你可能正在寻找

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

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

是什么:

while range(some_number):
    #do something