Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate in a cartesian product of lists

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:

('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
like image 894
alwbtc Avatar asked Sep 02 '12 15:09

alwbtc


People also ask

How do you create a Cartesian product in Python?

Get Cartesian Product in Python Using the itertools ModuleThe product(*iterables, repeat=1) method of the itertools module takes iterables as input and returns their cartesian product as output. The cartesian product order will be the order of each set/list in the provided argument iterables .

Can you iterate over lists?

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.


1 Answers

You want to use the product of the 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
like image 169
Martijn Pieters Avatar answered Oct 01 '22 14:10

Martijn Pieters