【问题标题】:All combinations of list wIthout itertools没有 itertools 的列表的所有组合
【发布时间】:2015-03-04 06:42:10
【问题描述】:

我正在尝试创建一个递归函数来查找 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:])

【问题讨论】:

  • 您的预期输出没有意义。你是怎么得到['a','a','b','c']['a','a'] 的?为什么有两个“a”?

标签: python list recursion combinations itertools


【解决方案1】:

正确的答案是你应该使用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)。然后添加相同大小 (N) 的 tail 组合。这就是您获得所有可能组合的方式。

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

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

【讨论】:

    【解决方案2】:

    似乎你想要一个列表的所有产品,你可以在下面的函数中使用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')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多