Если 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
:
Чтобы передать те же аргументы:
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)