Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何生成扁平列表的所有排列?_Python_List_Permutation_Combinatorics_Nested Lists - Fatal编程技术网

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

Python 如何生成扁平列表的所有排列?,python,list,permutation,combinatorics,nested-lists,Python,List,Permutation,Combinatorics,Nested Lists,如何在Python中生成平铺列表的所有排列。。。以保持列表中的顺序 榜样 输入 [[1,2], [3]] 产出 [1,2,3] [1,3,2] [3,1,2] 在排列中1总是在2之前。有趣的问题;我不确定itertools中是否有用于此目的的内置工具,但这似乎是可行的: 代码: 输出: 从排列生成器开始,通过检查所有输入子列表是否都是排列的子列表进行过滤。来自的子列表函数 l=[[1,2],[3]] def子列表(lst1、lst2): ls1=[如果lst2中的元素为lst1中的元素,则l

如何在Python中生成平铺列表的所有排列。。。以保持列表中的顺序

榜样

输入

[[1,2], [3]]
产出

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

在排列中1总是在2之前。

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

代码: 输出:
从排列生成器开始,通过检查所有输入子列表是否都是排列的子列表进行过滤。来自的子列表函数

l=[[1,2],[3]]
def子列表(lst1、lst2):
ls1=[如果lst2中的元素为lst1中的元素,则lst1中的元素为lst2中的元素]
ls2=[如果lst1中的元素为lst2中的元素,则lst2中的元素为lst2中的元素]
返回ls1==ls2
[itertools.permutations(itertools.chain.from_iterable(l))中的置换的置换
如果全部(l中l_el的子列表(l_el,perm)]
[(1, 2, 3), (1, 3, 2), (3, 1, 2)]

IIUC,您可以将其建模为在中查找所有拓扑排序,因此我建议您使用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施加了一个约束,即
1
总是在
2
之前出现。有关所有拓扑排序的更多信息,请参见。

请看一看。您能更好地解释一下如何生成输出吗?非常感谢大家与我一起思考。2个解决方案过滤掉所有可能的排列。当排列的数量与n一起运行时!这是不实际的。例如,输入[[1]、[2,3]、[4,5,6]、[7,8,9,10]、[11,12,13,14,15]]我们已经有15个了=13 biljon置换。我们知道,有效的排列必须从1,2,4,7,11开始,使得已经有2/3的排列无效。networkx解决方案可以非常快速地生成迭代器。我缺乏知识来检查它是否正确=以[1,2]、[3]、[4,5,6]、[7,8,9,10]、[11,12,13,14,15]]为输入,计算基于@RaySteam networkx的算法产生的37837800个排列,运行了将近41分钟。
[[3, 1, 2], [1, 2, 3], [1, 3, 2]]
Nodes: [1, 2, 3], Edges: [(1, 2)]