Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over combinations of items of multiple lists in Python

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?

like image 567
xuhdev Avatar asked Feb 12 '23 11:02

xuhdev


1 Answers

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
like image 100
Cory Kramer Avatar answered Feb 15 '23 01:02

Cory Kramer