可以不带i来做下面的事情吗?
for i in range(some_number):
# do something
如果你只是想做某件事N次而不需要迭代器。
可以不带i来做下面的事情吗?
for i in range(some_number):
# do something
如果你只是想做某件事N次而不需要迭代器。
当前回答
如果你真的想避免放一些有名字的东西(要么是OP中的迭代变量,要么是不想要的列表或不想要的生成器返回真想要的时间量),你可以这样做:
for type('', (), {}).x in range(somenumber):
dosomething()
使用的技巧是创建一个匿名类类型(",(),{}),这将导致一个具有空名称的类,但注意它不会插入到本地或全局名称空间中(即使提供了非空名称)。然后使用该类的成员作为迭代变量,这个迭代变量是不可达的,因为它所属的类是不可达的。
其他回答
现在您得到的不是一个不需要的计数器,而是一个不需要的列表。 最好的解决方案是使用一个以“_”开头的变量,这告诉语法检查器您知道您没有使用该变量。
x = range(5)
while x:
x.pop()
print "Work!"
#Return first n items of the iterable as a list
list(itertools.islice(iterable, n))
摘自http://docs.python.org/2/library/itertools.html
如果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)
你可能正在寻找
for _ in itertools.repeat(None, times): ...
这是Python中迭代次数最快的方法。
我们可以使用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)