如何生成扁平化列表列表的所有排列? [重复]

问题描述 投票:0回答:3

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

示例;

输入;

[[1,2], [3]]

输出;

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

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

python permutation
3个回答
1
投票

有趣的问题;我不确定itertools中是否有内置功能,但这似乎可行:

代码:

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

# [0, 0, 1]
l2 = [y for i, x in enumerate(l) for y in [i]*len(x)]

rv = []

for x in set(itertools.permutations(l2)):
    l = [[1,2], [3]]
    perm = []
    for i in x:
        perm.append(l[i].pop(0))
    rv.append(tuple(perm))

输出:

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

0
投票

从排列生成器开始,通过检查所有输入子列表是否是排列的子列表进行过滤。 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)]

0
投票

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:])]
dg = nx.DiGraph(edges)
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]]

对于提供的输入,将创建以下DiGraph:

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

拓扑排序强加了1总是要比2早出现的约束。

© www.soinside.com 2019 - 2024. All rights reserved.