简体   繁体   中英

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?

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 there are in fact 6 or 7 lists, it's probably worth going to itertools.product for readability. But for simple cases it's straightforward to use a list comprehension , and it requires no imports. For example:

alist = [1, 2, 3]
blist = ['A', 'B', 'C']
clist = ['.', ',', '?']

abc = [(a,b,c) for a in alist for b in blist for c in clist]

for e in abc:
    print("{}{}{} ".format(e[0],e[1],e[2])),

# 1A.  1A,  1A?  1B.  1B,  1B?  1C.  1C,  1C?  2A.  2A,  2A?  2B.  2B,  2B?  2C.  2C,  2C?  3A.  3A,  3A?  3B.  3B,  3B?  3C.  3C,  3C?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM