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?
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]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With