如何生成平展列表的所有排列?

2024-04-23 12:13:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中生成列表的平坦列表的所有排列。。。使列表中的顺序得以保持?你知道吗

举例说明

输入

[[1,2], [3]]

输出

[1,2,3]
[1,3,2]
[3,1,2]

在排列中,1总是在2之前。你知道吗


Tags: 列表顺序
3条回答

有趣的问题;我不确定itertools中是否有用于此的内置工具,但这似乎是可行的:

代码:

l = [[1,2], [3]]

# Create list containing indexes of sublists by the number of elements in that
# sublist - in this case [0, 0, 1]
l2 = [y for i, x in enumerate(l) for y in [i]*len(x)]

rv = []

# For every unique permutation of l2:
for x in set(itertools.permutations(l2)):
    l = [[1,2], [3]]
    perm = []
    # Create a permutation from l popping the first item of a sublist when
    # we come across that sublist's index
    for i in x:
        perm.append(l[i].pop(0))
    rv.append(tuple(perm))

输出:

>>> rv
[(3, 1, 2), (1, 3, 2), (1, 2, 3)]

从置换生成器开始,通过检查所有输入子列表是否都是置换的子列表来进行过滤。来自here的子列表函数。你知道吗

l = [[1,2], [3]]

def sublist(lst1, lst2):
   ls1 = [element for element in lst1 if element in lst2]
   ls2 = [element for element in lst2 if element in lst1]
   return ls1 == ls2

[perm for perm in itertools.permutations(itertools.chain.from_iterable(l))
 if all(sublist(l_el, perm) for l_el in l)]

[(1, 2, 3), (1, 3, 2), (3, 1, 2)]

IIUC,您可以将其建模为在DAG中查找所有拓扑排序,因此我建议您使用networkx,例如:

import itertools
import networkx as nx

data = [[1,2], [3]]
edges = [edge for ls in data for edge in zip(ls, ls[1:])]

# this creates a graph from the edges (e.g. [1, 2])
dg = nx.DiGraph(edges)

# add all the posible nodes (e.g. {1, 2, 3})
dg.add_nodes_from(set(itertools.chain.from_iterable(data)))

print(list(nx.all_topological_sorts(dg)))

输出

[[3, 1, 2], [1, 2, 3], [1, 3, 2]]

对于提供的输入,将创建以下有向图:

Nodes: [1, 2, 3], Edges: [(1, 2)]

一个topological sorting施加了1总是在2之前出现的约束。有关所有拓扑排序的更多信息,请参见here。你知道吗

相关问题 更多 >