如何从python中的二维列表中获取所有可能的项目组合?

时间:2011-11-23 22:17:36

标签: python list combinatorics

我没有找到更好的方法来在标题中说出这个问题。如果可以,请编辑。

我有一个像这样的列表列表:

a = [['a','b'],[1,2]]

现在,我想要一个能够像这样吐出所有可能组合的函数:

[['a',1],['a',2],['b',1],['b',2]]

预先知道a中的列表数量,也不提前知道每个子列表的长度,但所有出现的组合应包含每个子列表中的1个项目。

3 个答案:

答案 0 :(得分:12)

您需要itertools.product()

>>> list(itertools.product(*a))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]

答案 1 :(得分:0)

这可能是itertools.product()(Sven提到的)所做的事情:

def combs(list1, list2):
    results = []
    for x in list1:
        for y in list2:
            l.append([x,y])
    return results

答案 2 :(得分:0)

以下是使用递归的解决方案,combs_r具有accum摘要head(行中的下一个列表)以生成更加丰富的accum0,然后调用自身({1}}递归“)与tail(其余列表)和现在更胖的累积accum0

可能是内存的重度用户,因为每次调用combs_r都会添加一个新的命名空间,直到它全部解开时为止。 Python内部人员可以更多地了解这一点。

学习prolog,恕我直言。

def combs(ll):
    if len(ll) == 0:
        return []
    if len(ll) == 1:
         return [[item] for item in ll[0]]
    elif len(ll) == 2:
        return lmul(ll[0], [[item] for item in ll[1]])
    else:
        return combs_r(ll[1:], ll[0])

def combs_r(ll, accum):
    head = ll[0]
    tail = ll[1:]
    accum0 = []
    accum0 = lmul(head, accum)
    if len(tail) == 0:
        return accum0
    else:
        return combs_r(tail, accum0)

def lmul(head, accum):
    accum0 = []
    for ah in head:
        for cc in accum:
            #cc will be reused for each ah, so make a clone to mutate
            cc0 = [x for x in cc]
            cc0.append(ah)
            accum0.append(cc0)
    return accum0

sampleip = [['a','b','c'],[1,2], ['A', 'B']]
sampleip2 = [['a','b','c'],[1,2]]
sampleip1 = [['a','b','c']]
sampleip0 = []
print combs(sampleip0)
print combs(sampleip1)
print combs(sampleip2)
print combs(sampleip)
相关问题