Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python itertools: Best way to unpack product of product of list of lists

I have a list of lists over which I need to iterate 3 times (3 nested loops)

rangeList = [[-0.18,0.18],[0.14,0.52],[0.48,0.85]]

I can achieve this using product of product as follows

from itertools import product
for val in product(product(rangeList,rangeList),rangeList):
    print val

The output looks as follows

(([-0.18, 0.18], [-0.18, 0.18]), [-0.18, 0.18])
(([-0.18, 0.18], [-0.18, 0.18]), [0.14, 0.52])
(([-0.18, 0.18], [-0.18, 0.18]), [0.48, 0.85])
(([-0.18, 0.18], [0.14, 0.52]), [-0.18, 0.18])

Its a tuple of tuple. My questions are

  1. Is this a good approach?
  2. If so, what is the bestway to unpack the output of the product val into 3 separate variables say xRange, yRange and zRange, where each holds a list value of say [-0.18, 0.18] or [0.14, 0.52] etc.
like image 612
rambalachandran Avatar asked Feb 25 '16 20:02

rambalachandran


People also ask

Is Itertools product faster than for loops?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.

How do you get the Cartesian product of two lists in Python?

Practical Data Science using Python We have to find Cartesian product of these two lists. As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library.

How does Itertools permutations work?

The permutation tuples are emitted in lexicographic order according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value.

What is Islice?

islice() function This iterator selectively prints the values mentioned in its iterable container passed as an argument. Syntax: islice(iterable, start, stop, step)


1 Answers

This is probably the most elegant way to do what you want:

for xrange, yrange, zrange in product(rangeList, repeat=3):
    print xrange, yrange, zrange

But just to demonstrate how you can do the "deep" tuple unpacking you were trying:

for (xrange, yrange), zrange in product(product(rangeList,rangeList),rangeList):
    print xrange, yrange, zrange
like image 89
shx2 Avatar answered Nov 14 '22 23:11

shx2