How to iterate in a cartesian list product

I would like to iterate in a for loop using 3 (or any number) of lists with any number of elements, for example:

from itertools import izip
for x in izip(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):
    print x

but it gives me:

('AAA', 'M', '00:00')
('BBB', 'Q', '01:00')
('CCC', 'S', '02:00')

I want to:

('AAA', 'M', '00:00')
('AAA', 'M', '01:00')
('AAA', 'M', '02:00')
.
.

('CCC', 'B', '03:00')

Actually I want this:

for word, letter, hours in [cartesian product of 3 lists above]
    if myfunction(word,letter,hours):
       var_word_letter_hours += 1
+5
source share
3 answers

Do you want to use product lists:

from itertools import product

for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):

Demo:

>>> from itertools import product
>>> for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):
...     print word, letter, hours
... 
AAA M 00:00
AAA M 01:00
AAA M 02:00
AAA M 03:00
...
CCC B 00:00
CCC B 01:00
CCC B 02:00
CCC B 03:00
+13
source

Use itertools.product:

import itertools

for x in itertools.product(["AAA", "BBB", "CCC"],
                           ["M", "Q", "S", "K", "B"],
                           ["00:00", "01:00", "02:00", "03:00"]):
    print x

output:

('AAA', 'M', '00:00')
('AAA', 'M', '01:00')
...
('CCC', 'B', '02:00')
('CCC', 'B', '03:00')
+4
source

for :

for a in ["AAA", "BBB", "CCC"]:
    for b in ["M", "Q", "S", "K", "B"]:
       for c in ["00:00", "01:00", "02:00", "03:00"]:
           x = (a, b, c)
           # Use x ...

-, , /, itertools.product. , ; , , , ( product(*lists)).

0

All Articles