开发者

python input for itertools.product

Looking for a way to simulate nested loops (or a c开发者_StackOverflowartesian product) i came across the itertools.product function. i need a function or piece of code that receive a list of integers as input and returns a specific generator.

example:

input = [3,2,4] -> gen = product(xrange(3),xrange(2),xrange(4))

or

input = [2,4,5,6] -> gen = product(xrange(2),xrange(4),xrange(5),xrange(6))

as the size of the lists varies i am very confused in how to do that without the need of a lot of precoding based on a crazy amount of ifs and the size of the list.

also is there a difference in calling product(range(3)) or product(xrange(3))?


def bigproduct(*args):
  newargs = [xrange(x) for x in args]
  return itertools.product(*newargs)

for i in bigproduct(3, 2, 4):
   ....

range() generates a list up-front, therefore uses time up front and more space, but takes less time to get each element. xrange() generates each element on the fly, so takes up less space and initial time, but takes more time to return each element.


This can be easily accomplished using map:

from itertools import product
for i in product(*map(range, shape)):
    print i
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜