Skip to main content
 首页 » 编程设计

python之如何生成扁平列表列表的所有排列

2025年05月04日18tintown

如何在 Python 中生成扁平列表列表的所有排列,...以便保持列表中的顺序?

例子;

输入;

[[1,2], [3]] 

输出;

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

在排列中 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)] 

A topological sorting强加了 1 总是出现在 2 之前的约束。可以找到有关所有拓扑排序的更多信息,here .