如何从多个列表中获取所有组合?

9

我不确定我的问题是否正确,但我不知道该如何用其他方式解释它。所以我有一些列表,例如

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']

我需要获得类似以下的内容:

result = [
    ['11', '21', '31'],
    ['11', '21', '32'],
    ['11', '22', '31'],
    ['11', '22', '32'],
    ['12', '21', '31'],
    ['12', '21', '32'],
    ['12', '22', '31'],
    ['12', '22', '32']
]

请先自行研究你的问题,将你的问题标题复制到谷歌中会出现多个重复结果。 - Sayse
如果所有的列表长度都是两个,那么它看起来像是一个二进制计数系统,因此你可以使用算法来实现,但使用itertools的帖子是正确的。 - Alessi 42
5个回答

7
你需要使用 itertools.product 来返回输入可迭代对象的笛卡尔积。
>>> a = ['11', '12']
>>> b = ['21', '22']
>>> c = ['31', '32']
>>>
>>> from itertools import product
>>>
>>> list(product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]

您可以使用列表推导式将元组转换为列表:

>>> [list(i) for i in product(a,b,c)]
[['11', '21', '31'], ['11', '21', '32'], ['11', '22', '31'], ['11', '22', '32'], ['12', '21', '31'], ['12', '21', '32'], ['12', '22', '31'], ['12', '22', '32']]

4

用户使用itertoolscombinations

import itertools
a = ['11', '12']
b = ['21', '22']
c = ['31', '32']
list(itertools.combinations(itertools.chain(a,b,c), 3))
[('11', '12', '21'), ('11', '12', '22'), ('11', '12', '31'), ('11', '12', '32'), ('11', '21', '22'), ('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('11', '31', '32'), ('12', '21', '22'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32'), ('12', '31', '32'), ('21', '22', '31'), ('21', '22', '32'), ('21', '31', '32'), ('22', '31', '32')]

或者product函数:

list(itertools.product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]

1
“combinations” 会产生一些使用同一个列表中的2个元素的结果。 - Uriel

0
一个不使用任何库的解决方案:
def subproblem(list_a, list_b):
    c = list()
    for i, a_i in enumerate(list_a):
        for j, b_j in enumerate(list_b):
            c.append(a_i + [b_j])
    return c


def multi_lists_find_all_combination(lists):
    com = [[]]
    if len(lists) == 1:
        return lists[0]
    for i in range(0, len(lists)):
        print(i)
        com = subproblem(com, lists[i])
    return com

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']

ans = multi_lists_find_all_combination([a,b,c])


0
import itertools
list(itertools.product(a,b,c))

或者使用numpy

import numpy
[list(x) for x in numpy.array(numpy.meshgrid(a,b,c)).T.reshape(-1,len(a))]

0
import numpy as np    
np.array(np.meshgrid(a, b, c)).T.reshape(-1,3)

编辑

import numpy as np 
len = 3 #combination array length
np.array(np.meshgrid(a, b, c)).T.reshape(-1,len)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接