![](/img/trans.png)
[英]Generate all permutations of a list and permutations of the possible lists within that list?
[英]How to generate all permutations of the flattened list of 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)]
有趣的問題; 我不確定 itertools 中是否有內置函數,但這似乎可行:
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))
>>> rv
[(3, 1, 2), (1, 3, 2), (1, 2, 3)]
從排列生成器開始,通過檢查所有輸入子列表是否是排列的子列表來過濾。 子列表功能來自這里。
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.