列表的所有组合与没有itertools

时间:2015-03-04 06:42:10

标签: python list recursion combinations itertools

我正在尝试创建一个递归函数,找到python列表的所有组合。

我想在我的函数中输入['a','b','c']并且当函数运行时我希望跟踪看起来像这样:

   ['a','b','c']  
   ['['a','a'],['b','a'],['c','a']]      
   ['['a','a','b'],['b','a','b'],['c','a','b']]      
   ['['a','a','b','c'],['b','a','b','c'],['c','a','b','c']]

我的递归函数如下所示:

def combo(lst,new_lst = []):
    for item in lst:
        new_lst.append([lst[0],item])
        print([lst[0],item])
    return combo(new_lst,lst[1:])

2 个答案:

答案 0 :(得分:5)

正确的答案是你应该使用itertools.combinations。但如果由于某种原因你不想,并想要编写递归函数,你可以使用下面的代码。它是对erlang生成组合方式的改编,所以起初看起来有点奇怪:

def combinations(N, iterable):
    if not N:
        return [[]]
    if not iterable:
        return []

    head = [iterable[0]]
    tail = iterable[1:]
    new_comb = [ head + list_ for list_ in combinations(N - 1, tail) ]

    return new_comb + combinations(N, tail)

这是一种非常优雅的方式来考虑大小N的组合:你采用可迭代的第一个元素( head )并将其与较小的(N-1)结合起来可迭代其余部分的组合( tail )。然后,将 tail 的相同大小(N)组合添加到其中。这就是你如何得到所有可能的组合。

如果您需要所有长度的所有组合:

for n in range(1, len(iterable) + 1):
    print(combinations(n, iterable))

答案 1 :(得分:0)

似乎您想要列表中的所有产品,您可以在以下函数中使用itertools.product来返回生成器列表:

>>> from itertools import product
>>> def pro(li):
...       return [product(l,repeat=i) for i in range(2,len(l)+1)]
... 
>>> for i in pro(l):
...     print list(i)
... 
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]
相关问题