可以不带i来做下面的事情吗?
for i in range(some_number):
# do something
如果你只是想做某件事N次而不需要迭代器。
可以不带i来做下面的事情吗?
for i in range(some_number):
# do something
如果你只是想做某件事N次而不需要迭代器。
当前回答
你可能正在寻找
for _ in itertools.repeat(None, times): ...
这是Python中迭代次数最快的方法。
其他回答
是什么:
while range(some_number):
#do something
也许答案取决于你在使用迭代器时遇到了什么问题? 可能会使用
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)
我们可以使用while & yield,我们可以像这样创建自己的循环函数。在这里你可以参考官方文件。
def my_loop(start,n,step = 1):
while start < n:
yield start
start += step
for x in my_loop(0,15):
print(x)
这里有一个随机的想法,利用(滥用?)数据模型(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
我想知道在标准库中是否有类似的东西?