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

标签 python list permutation combinatorics nested-lists

如何在 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 .

关于python - 如何生成扁平列表列表的所有排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59194314/

相关文章:

html - 当我在 li 中使用 float 时,list-style-type 在 IE 7 中不起作用

list - 消除Scheme中列表中的空列表

java - 在Java中统一生成随机排列

python - 有效地生成所有排列

来自并行文件的 Python 元组

python - 将数据框列的列表拆分为两个数据框列

python - 从 for 循环返回的元素中追加一个新列表

python - 如何在flask中使用after_request关闭数据库连接和python?

python - 理解列表的问题(我认为)

ruby - 执行位于数组内的 ruby​​ 语句