如何通过python中的订单列表对多个列表进行排序?

时间:2020-02-25 06:44:23

标签: python

我有三个列表:

One = [[[1.1, 1.2, 1.3, 1.4], [2.1, 2.2, 2.3, 2.4], [3.1, 3.2, 3.3, 3.4]], 
       [[4.1, 4.2, 4.3, 4.4], [5.1, 5.2, 5.3, 5.4], [6.1, 6.2, 6.3, 6.4]]]
Two = [[[1], [2], [3]], 
       [[4], [5], [6]]]
sort_order = [[[5], [1], [3]], 
              [[2], [8], [5]]]

我想按One的值对列表Twosort_order进行排序。也就是说,对于列表OneTwo中的每个元素,将按sort_order中元素的值进行排序。在对列表OneTwo进行排序之后,变为:

One = [[[2.1, 2.2, 2.3, 2.4], [3.1, 3.2, 3.3, 3.4], [1.1, 1.2, 1.3, 1.4]], 
       [[4.1, 4.2, 4.3, 4.4], [6.1, 6.2, 6.3, 6.4], [5.1, 5.2, 5.3, 5.4]]]  

Two = [[[2], [3], [1]], 
       [[4], [6], [5]]]

1 个答案:

答案 0 :(得分:0)

我希望…列表“ One”和“ Two”中的每个元素都按“ sort_order” 中的元素值进行排序。

您可以通过按排序顺序对索引范围进行排序来生成排序索引,然后使用这些索引重新排列列表元素。

sort_index = [sorted(range(len(l)), key=lambda i: l[i]) for l in sort_order]
# sort_index now contains the needed order elements: [[1, 2, 0], [0, 2, 1]]
# with that, we can simply rearrange our lists:
One = [[l[j] for j in i] for l, i in zip(One, sort_index)]
Two = [[l[j] for j in i] for l, i in zip(Two, sort_index)]

或者,如果您想就地修改列表,

sort_index = [sorted(range(len(l)), key=lambda i: l[i]) for l in sort_order]
for l, i in zip(One, sort_index): l[:] = [l[j] for j in i]
for l, i in zip(Two, sort_index): l[:] = [l[j] for j in i]
相关问题