如果do_something是一个简单的函数或者可以封装在一个函数中,一个简单的map()可以do_somethingrange(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)