I have several lists and I need to do something with each possible combination of these list items. In the case of two lists, I can do:
for a in alist:
for b in blist:
# do something with a and b
However, if there are more lists, say 6 or 7 lists, this method seems reluctant. Is there any way to elegantly implement this iteration?
You could use itertools.product
to make all possible combinations from your lists. The result will be one long list of tuple
with an element from each list in the order you passed the list in.
>>> a = [1,2,3]
>>> b = ['a', 'b', 'c']
>>> c = [4,5,6]
>>> import itertools
>>> list(itertools.product(a,b,c))
[(1, 'a', 4), (1, 'a', 5), (1, 'a', 6), (1, 'b', 4), (1, 'b', 5), (1, 'b', 6), (1, 'c', 4), (1, 'c', 5), (1, 'c', 6),
(2, 'a', 4), (2, 'a', 5), (2, 'a', 6), (2, 'b', 4), (2, 'b', 5), (2, 'b', 6), (2, 'c', 4), (2, 'c', 5), (2, 'c', 6),
(3, 'a', 4), (3, 'a', 5), (3, 'a', 6), (3, 'b', 4), (3, 'b', 5), (3, 'b', 6), (3, 'c', 4), (3, 'c', 5), (3, 'c', 6)]
For example
for ai, bi, ci in itertools.product(a,b,c):
print ai, bi, ci
Output
1 a 4
1 a 5
1 a 6
... etc
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