简体   繁体   English

在 Python 中迭代多个列表的项目组合

[英]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.但是,如果有更多的列表,比如 6 或 7 个列表,这种方法似乎不太情愿。 Is there any way to elegantly implement this iteration?有没有办法优雅地实现这个迭代?

You could use itertools.product to make all possible combinations from your lists.您可以使用itertools.product从您的列表中进行所有可能的组合。 The result will be one long list of tuple with an element from each list in the order you passed the list in.结果将是一个长长的tuple列表,每个列表中的元素按照您传入列表的顺序排列。

>>> 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.如果实际上有 6 或 7 个列表,为了可读性,可能值得去itertools.product But for simple cases it's straightforward to use a list comprehension , and it requires no imports.但是对于简单的情况,使用list comprehension很简单,并且不需要导入。 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?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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