简体   繁体   English

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

[英]How to generate all permutations of the flattened list of lists?

How to generate all permutations of the flattened list of lists in Python, ... such that the order in the lists is maintained?如何在 Python 中生成扁平列表列表的所有排列,...以便保持列表中的顺序?

Example;例子;

input;输入;

[[1,2], [3]]

output;输出;

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

1 is always before 2 in the permutations.在排列中,1 总是在 2 之前。

IIUC, you could model this as finding all topological sorts in a DAG , so I suggest you use networkx, for example: 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)))

Output输出

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

For the input provided, the following DiGraph is created:对于提供的输入,将创建以下有向图:

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

A topological sorting imposes the constraint that 1 is always going to be present before 2 .拓扑排序强加了1总是在2之前出现的约束。 More on all topological sortings can be found, here .可以在此处找到有关所有拓扑排序的更多信息

Interesting problem;有趣的问题; I'm not sure whether there is a builtin in itertools for this, but this would seem to work:我不确定 itertools 中是否有内置函数,但这似乎可行:

Code:代码:

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))

Output:输出:

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

Starting from the permutations generator, filter by checking that all input sublists are sublists of the permutations.从排列生成器开始,通过检查所有输入子列表是否是排列的子列表来过滤。 Sublist function from 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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM