如何使用另一个列表对多维列表进行排序

How to Order a multidimensional List using another list

快速总结:

need_to_reorder = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]

我想为need_to_reorder[0][x]设置订单x 使用我的排序数组的值

sorting_array = [1, 3, 0, 2]

要求的结果:need_to_reorder将等于

[['b', 'd', 'a', 'c'], [2, 4, 1, 3]] 

寻找答案,我尝试使用 numPy:

import numpy as np
sorting_array = [1, 3, 0, 2]
i = np.array(sorting_array)
print i  ## Results: [1 3 0 2] <-- No Commas?
need_to_reorder[:,i]

结果:

TypeError: list indicies must be integers, not tuple

我正在寻找对上述代码的更正或完全不同的方法。

你可以试试简单的嵌套理解

>>> l = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
>>> s = [1, 3, 0, 2]
>>> [[j[i] for i in s] for j in l]
[['b', 'd', 'a', 'c'], [2, 4, 1, 3]]

如果你需要这个作为一个函数,你可以有一个非常简单的函数,如

def reorder(need_to_reorder,sorting_array)
    return [[j[i] for i in sorting_array] for j in need_to_reorder]

请注意,这也可以使用 map 函数来解决。然而,在这种情况下,列表 comp 是首选,因为 map 变体需要 lambda 函数。 map 和 list-comp 之间的区别在 answer

中进行了完整的讨论
def order_with_sort_array(arr, sort_arr):
    assert len(arr) == len(sort_arr)
    return [arr[i] for i in sort_arr]

sorting_array = [1, 3, 0, 2]
need_to_reorder = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]

after_reordered =  map(lambda arr : order_with_sort_array(arr, sorting_array), 
                      need_to_reorder)

这应该有效

import numpy as np
ntr = np.array([['a', 'b', 'c', 'd'], [1, 2, 3, 4]])
sa = np.array([1, 3, 0, 2])
print np.array( [ntr[0,] , np.array([ntr[1,][sa[i]] for i in range(sa.shape[0])])] )
>> [['a' 'b' 'c' 'd'],['2' '4' '1' '3']]