【问题标题】:Permutations of the elements of two lists with order restrictions具有顺序限制的两个列表的元素排列
【发布时间】:2014-10-11 02:00:41
【问题描述】:

我想将两个输入列表合并在一起并获取它们元素的所有排列,以便保留每个输入列表中元素的顺序。

例如,如果我有两个列表:['b','a']['c','d'],我想获得以下列表:

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

保留原始列表中元素的顺序(b 在 a 之前,c 在 d 之前)。

我发现了一篇处理类似问题但使用字符串作为输入而不是列表的帖子:Restricted Permutations of Strings in Python。例如,将字符串“ba”和“cd”作为输入,将返回字符串“bacd”、“bcad”、“bcda”、“cbad”、“cbda”、“cdba”。

我已尝试调整那里的代码以适应我的问题,但没有奏效。使用与上面相同的示例,我得到 [None, None, None, None, None, None] 而不是我期望的 6 个列表。下面是我使用的代码。

def ordered_permutations(list1, list2):
    perms = []
    if len(list1) + len(list2) == 1:
        return [list1 or list2]
    if list1:
        for item in ordered_permutations(list1[1:], list2):
            perms.append([list1[0]].append(item))
    if list2:
        for item in ordered_permutations(list1, list2[1:]):
            perms.append([list2[0]].append(item))
    return perms

【问题讨论】:

  • list.append 是一个就地操作,按照 Python 的惯例,因此返回 None
  • list.append 返回None。你想要perms.append([list1[0]] + item)
  • 谢谢!我用perms.append([list1[0]] + item) 替换了perms.append([list1[0]].append(item)),它成功了!

标签: python list permutation


【解决方案1】:

list.append() 返回None,因为列表已就地更改。您应该改用串联:

def ordered_permutations(list1, list2):
    perms = []
    if len(list1) + len(list2) == 1:
        return [list1 or list2]
    if list1:
        for item in ordered_permutations(list1[1:], list2):
            perms.append([list1[0]] + item)
    if list2:
        for item in ordered_permutations(list1, list2[1:]):
            perms.append([list2[0]] + item)
    return perms

这会产生你需要的输出:

>>> def ordered_permutations(list1, list2):
...     perms = []
...     if len(list1) + len(list2) == 1:
...         return [list1 or list2]
...     if list1:
...         for item in ordered_permutations(list1[1:], list2):
...             perms.append([list1[0]] + item)
...     if list2:
...         for item in ordered_permutations(list1, list2[1:]):
...             perms.append([list2[0]] + item)
...     return perms
... 
>>> for combo in ordered_permutations(['b','a'], ['c', 'd']):
...     print combo
... 
['b', 'a', 'c', 'd']
['b', 'c', 'a', 'd']
['b', 'c', 'd', 'a']
['c', 'b', 'a', 'd']
['c', 'b', 'd', 'a']
['c', 'd', 'b', 'a']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 2022-12-18
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多