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
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 .
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.
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
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