我有一个列表列表,我想将列表与特定订单合并。见例:
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]
答案 0 :(得分:2)
你可以使用其他一些技巧,比如理解。以下将返回一个单位列表:
return [part for order in orders for i in order for part in parts[i]]
以下将返回2D列表:
return [[part for i in order for part in parts[i]] for order in orders]
答案 1 :(得分:1)
此解决方案与您提议的解决方案基本相同,但使用列表解析更多Python式。
>>> def merge_lists(desired_order):
... merged_list = [element for i in desired_order for element in parts[i]]
... return merged_list
...
>>> desired_order = orders[0]
>>> merge_lists(desired_order)
[2, 6, 1, 4, 0, 3, 7, 5]
答案 2 :(得分:1)
只需在索引上调用itertools.chain并与 operator.itemgetter 结合使用:
frIn [9]: groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
In [10]: orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Ord
In [11]: from itertools import chain
In [12]: from operator import itemgetter
In [13]: [list(chain(*itemgetter(*o)(groups))) for o in orders]
[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]
在您自己的代码中,您只返回最后一个LC,因此无法正常工作:
for order in orders:
LC = [] # overwritten each iteration so you only get the last sublists.
for i in order:
LC += parts[i]
return LC
答案 3 :(得分:0)
inputs = [[1,2,3], [4,5,6], [7]]
orders = [[0,1,2], [2,1,0]]
result = [input_element for order in orders for order_element in order for input_element in inputs[order_element]]
print(result)