遍历Python中多个列表的项目组合 [英] Iterate over combinations of items of multiple lists in Python

查看:74
本文介绍了遍历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

但是,如果有更多列表(例如6或7个列表),则此方法似乎不太愿意.有什么方法可以优雅地实现此迭代吗?

However, if there are more lists, say 6 or 7 lists, this method seems reluctant. Is there any way to elegantly implement this iteration?

推荐答案

您可以使用itertools.product从列表中进行所有可能的组合.结果将是一个tuple的长列表,其中每个列表中的元素均按传递列表的顺序排列.

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 ai, bi, ci in itertools.product(a,b,c):
    print ai, bi, ci

输出

1 a 4
1 a 5
1 a 6
... etc

这篇关于遍历Python中多个列表的项目组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆