繁体   English   中英

如何在 Python 中使用递归编织两个列表

[英]How to weave two lists using recursion in Python

我想编织两个列表并输出所有可能的结果。
例如,
输入:两个列表 l1 = [1, 2], l2 = [3, 4]
输出:[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 4, 2], [3, 1, 2, 4], [3, 1, 4, 2 ], [3, 4, 1, 2]
注意:我需要保持每个列表中的顺序(例如 1 总是在 2 之前,而 3 总是在 4 之前)

我解决这个问题的方法是从一个列表中删除头部,递归,然后对另一个列表做同样的事情。 代码如下:

all_possibles = []
def weaveLists(first, second, added):
    if len(first) == 0 or len(second) == 0:
        res = added[:]
        res += first[:]
        res += second[:]
        all_possibles.append(res)
        return

    cur1 = first[0]
    added.append(cur1)
    first = first[1:]
    weaveLists(first, second, added)
    added = added[:-1]
    first = [cur1] + first

    cur2 = second[0]
    added.append(cur2)
    second = second[1:]
    weaveLists(first, second, added)
    added = added[:-1]
    second = [cur2] + second


weaveLists([1, 2], [3, 4], [])
print(all_possibles)

我得到的结果是: [[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 4, 2], [1, 3, 1, 2, 4], [ 1, 3, 1, 4, 2], [1, 3, 1, 4, 1, 2]]

我不明白为什么对于最后三个列表,第一个列表中的标题 1 没有被删除。

任何人都可以帮忙吗? 谢谢!

这是另一种方法:我们生成编织列表中第一个列表项的可能索引,并相应地填充列表。

我们可以用itertools.combinations生成索引:它是编织列表的索引的组合,每次都取它们的 len(first_list) 。

from itertools import combinations
​
def weave(l1, l2):
    total_length = len(l1) + len(l2)
    # indices at which to put items from l1 in the weaved output
    for indices in combinations(range(total_length), r=len(l1)):
        out = []
        it1 = iter(l1)
        it2 = iter(l2)
        for i in range(total_length):
            if i in indices:
                out.append(next(it1))
            else:
                out.append(next(it2))
        yield out

示例运行:

l1 = [1, 2]
l2 = [3, 4]
​
for w in weave(l1, l2):
    print(w)
    
​
[1, 2, 3, 4]
[1, 3, 2, 4]
[1, 3, 4, 2]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]

另一个带有更长列表的示例运行:

l1 = [1, 2]
l2 = [3, 4, 5]
​
for w in weave(l1, l2):
    print(w)
    
​
[1, 2, 3, 4, 5]
[1, 3, 2, 4, 5]
[1, 3, 4, 2, 5]
[1, 3, 4, 5, 2]
[3, 1, 2, 4, 5]
[3, 1, 4, 2, 5]
[3, 1, 4, 5, 2]
[3, 4, 1, 2, 5]
[3, 4, 1, 5, 2]
[3, 4, 5, 1, 2]

你得到这些意外结果的原因是你在这个地方added了 mutate:

added.append(cur1)

...这会影响调用者的added列表(无意中)。 虽然“撤消”操作不会改变列表:

added = added[:-1]

这将创建一个新的列表,因此,这种“撤销”操作不会回滚在来电者名单的变化。

简单的解决方法是将调用append替换为:

added = added + [cur1]

同样的情况也应该发生在第二个块中。

如果您即时传递递归调用的新值,并将这两个代码块替换为:

weaveLists(first[1:], second, added + [first[0]])
weaveLists(first, second[1:], added + [second[0]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM