-2

我有三个列表:

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_orderOneTwosort_orderOneTwo

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]]]
4

1 回答 1

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]
于 2020-02-25T10:11:54.010 回答