我有三个列表:
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
的值对列表Two
和sort_order
进行排序。也就是说,对于列表One
和Two
中的每个元素,将按sort_order
中元素的值进行排序。在对列表One
和Two
进行排序之后,变为:
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]]]
答案 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]