Python itertools: best way to unzip a product of a list of products

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 the product product as follows

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

The result is 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]) 

His motorcade is a motorcade. My questions

  • Is this a good approach?
  • If so, what is the best way to unpack the output of the val product into 3 separate variables: xRange , yRange and zRange , where each has a list value, for example [-0.18, 0.18] or [0.14, 0.52] , etc.
+5
source share
1 answer

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 unpack "deep" tuples, you tried:

 for (xrange, yrange), zrange in product(product(rangeList,rangeList),rangeList): print xrange, yrange, zrange 
+10
source

Source: https://habr.com/ru/post/1243888/


All Articles