我有列表的列表,我想合并具有特定顺序的列表。看例如:按特定顺序合并列表
id list 0 1 2
[[0], [2, 6, 1, 4], [3, 7, 5]]
Order Resulting List
[1, 0, 2] = [2, 6, 1, 4, 0, 3, 7, 5]
[0, 2, 1] = [0, 3, 7, 5, 2, 6, 1, 4]
[2, 1, 0] = [3, 7, 5, 2, 6, 1, 4, 0]
有人可以建议一个更优雅的算法,提出下面?
groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[1, 0, 2], [0, 2, 1], [2, 1, 0]]
for order in orders:
LC = []
for i in order:
LC += groups[i]
return LC
让我解释一下好一点什么,我需要:
groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Order of each group in LC
solutions = [] # I want to put the created LC here
for order in orders:
LC = [] # I need this because a want LCs individualy and not one with all
for i in order: # for each order I pick de index (i) of the group
LC += grupos[i] # and merge then according with index of group
solutions.append([LC])
print(solutions)
我想这(对每一个订单一个LC):
[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
,而不是这样的:
[0, 3, 7, 5, 2, 6, 1, 4, 2, 6, 1, 4, 0, 3, 7, 5, 3, 7, 5, 2, 6, 1, 4, 0]
上面的算法工作,但需要一个另一个更优雅和高效。
输出的一些例子:
groups = [[0], [2, 1], [3, 7, 5], [4], [6]]
Order = [1, 0, 2, 3, 4]
LC = [2, 1, 0, 3, 7, 5, 4, 6]
[2, 1, 0, 3, 4]
[3, 7, 5, 2, 1, 0, 4, 6]
[3, 1, 2, 0, 4]
[4, 2, 1, 3, 7, 5, 0, 6]
[4, 1, 2, 3, 0]
[6, 2, 1, 3, 7, 5, 4, 0]
[0, 2, 1, 3, 4]
[0, 3, 7, 5, 2, 1, 4, 6]
[0, 3, 2, 1, 4]
[0, 4, 3, 7, 5, 2, 1, 6]
[0, 4, 2, 3, 1]
[0, 6, 3, 7, 5, 4, 2, 1]
[0, 1, 3, 2, 4]
[0, 2, 1, 4, 3, 7, 5, 6]
[0, 1, 4, 3, 2]
[0, 2, 1, 6, 4, 3, 7, 5]
[0, 1, 2, 4, 3]
[0, 2, 1, 3, 7, 5, 6, 4]
您的代码似乎不起作用。您每次迭代创建一个新LC只返回最后一个LC。你期待什么作为输出? –
在我的机器上工作,我把它放在输出下面。 “解决方案”列表存储所有LC创建的列表。 – HarpMan
您的初始代码与您编辑的代码不同。 –