Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use itertools in python to clean up nested iterations? [duplicate]

Let's say I have the following code:

a = [1,2,3]
b = [2,4,6]
c = [3,5,7]

for i in a:
  for j in b:
    for k in c:
      print i * j * k

Is there a way I can consolidate an iterator in one line instead of making it nested?

like image 577
Skorpius Avatar asked Oct 18 '16 18:10

Skorpius


1 Answers

Use itertools.product within a list comprehension:

In [1]: from itertools import product
In [5]: [i*j*k for i, j, k in product(a, b, c)]
Out[5]: 
[6,
 10,
 14,
 12,
 20,
 28,
 18,
 30,
 42,
 12,
 20,
 28,
 24,
 40,
 56,
 36,
 60,
 84,
 18,
 30,
 42,
 36,
 60,
 84,
 54,
 90,
 126]
like image 141
Mazdak Avatar answered Nov 15 '22 19:11

Mazdak