0

I have a list of lists, and would like to generate a list of lists consisting of one element from each list.

For example, given the lists [[1, 2], [3, 4], [5, 6], [7, 8], I would execute the following code [(i, j, k, h) for i in [1, 2] for j in [3, 4] for k in [5, 6] for h in [7, 8]] and gets as output

[(1, 3, 5, 7), (1, 3, 5, 8), (1, 3, 6, 7), (1, 3, 6, 8), (1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 3, 5, 7), (2, 3, 5, 8), (2, 3, 6, 7), (2, 3, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8)]

This code does not adapt for list of lists with different number of sub-lists. Is there a way to use nested list comprehensions to achieve the desired result? (My sub-lists are not always of the same length).

Vincent Tjeng
  • 693
  • 8
  • 25

1 Answers1

5

Use itertools.product, and unpack the list when pass as argument:

In [40]: from itertools import product

In [41]: list(product(*[[1, 2], [3, 4], [5, 6], [7, 8]]))
Out[41]: 
[(1, 3, 5, 7),
 (1, 3, 5, 8),
 (1, 3, 6, 7),
 (1, 3, 6, 8),
 (1, 4, 5, 7),
 (1, 4, 5, 8),
 (1, 4, 6, 7),
 (1, 4, 6, 8),
 (2, 3, 5, 7),
 (2, 3, 5, 8),
 (2, 3, 6, 7),
 (2, 3, 6, 8),
 (2, 4, 5, 7),
 (2, 4, 5, 8),
 (2, 4, 6, 7),
 (2, 4, 6, 8)]
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108