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

2024-04-20 05:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我没有找到更好的方式来表达这个问题的标题。如果可以,请编辑。在

我有一份清单,清单如下:

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

现在,我想要一个函数,它可以输出所有可能的组合,如下所示:

^{pr2}$

其中,a中的列表数目也不是预先知道的,每个子列表的长度也不是预先知道的,但是所有出来的组合应该包含每个子列表中的1个项。在


Tags: 函数编辑标题列表方式数目pr2
3条回答

您需要^{}

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

这可能是itertools.product()(Sven提到的)的作用:

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

这里有一个使用递归的解决方案,combs_raccum摘要head(行中的下一个列表)来生成一个更胖的{},然后用tail(剩余列表)和现在更胖的累加器accum0调用自己(“递归”)。在

由于每次调用combs_r都会添加一个新的名称空间,因此可能会占用大量内存,直到所有调用都解除为止。在Python内部更熟悉的人可能会对此发表评论。在

学习序言是值得的,伊荷。在

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)

相关问题 更多 >