【问题标题】:How to combine (chain) lists recursively?如何递归组合(链)列表?
【发布时间】:2017-08-02 07:11:25
【问题描述】:

由于某种原因,我很难理解递归算法...

我想知道是否有人可以帮我想出以下的递归版本:

我有一个数字列表,我想获取所有元素的所有可能排列列表。

例如,给定[[1], [2,3], [4,5]],我希望输出为:

[[1,2,3,4,5], [1,2,3,5,4], [1,3,2,4,5], [1,3,2,5,4]]

我这样做的方式有点丑:

l = (my list)
perms = [list(permutations(i)) for i in l]
p = perms[0]
for i in range(1, len(perms)):
    p = list(map(lambda x: list(chain.from_iterable(x)), list(product(p, perms[i]))))
    i += 1
print(p)

我不喜欢它......我觉得递归可能更优雅。 有什么想法吗?

【问题讨论】:

    标签: python algorithm python-3.x recursion permutation


    【解决方案1】:

    无需递归即可简化代码:

    >>> from itertools import chain, product, permutations
    >>> l = [[1], [2,3], [4,5]]
    >>> perms = [list(permutations(x)) for x in l]
    >>> [list(chain.from_iterable(xs)) for xs in product(*perms)]
    [[1, 2, 3, 4, 5], [1, 2, 3, 5, 4], [1, 3, 2, 4, 5], [1, 3, 2, 5, 4]]
    

    对于product(*perms),请参阅Unpacking Argument Lists - Python tutorial

    【讨论】:

      【解决方案2】:

      你可以简化很多事情。只需将所有排列迭代器传递给 itertools.product 并展平您得到的列表列表:

      my_list = [[1], [2,3], [4,5]]
      perms = [permutations(x) for x in my_list]
      result = [list(chain.from_iterable(product)) for product in product(*perms)]
      

      【讨论】:

        猜你喜欢
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-05
        相关资源
        最近更新 更多