【问题标题】:Sort a list of arrays using the sort of other array python使用其他数组python的排序对数组列表进行排序
【发布时间】:2020-07-15 17:16:54
【问题描述】:

我有两个列表:一个二维数组列表和它的生成时间,它是一个整数。它们的长度为 N 并且都“同样无序”。所以通过使用索引对列表进行排序'time'我可以对二维数组列表进行排序。

我想做这样的事情:

ordered_list_of_arrays = np.asarray(disordered_list).argsort(np.asarray(time))
ordered_time = np.asarray(time).sort()

另一种选择是将其保留为列表:

ordered_arrays = disordered_list[np.argsort(np.asarray(time))]
TypeError: only integer scalar arrays can be converted to a scalar index

通过迭代 np.argsort(time) 我可以对我的disordered_list 进行排序,但我想知道是否有更好的选择或最好的选择。

谢谢

【问题讨论】:

  • li.sort(key=lambda x:time_list.index(x))

标签: python arrays sorting np.argsort


【解决方案1】:

创建一个索引数组并根据 time_list 的值对其进行排序。然后使用这些索引来构造两个数组的排序版本。

代码:

def sorted_lists(time_list, array_list):
    sorted_indices = sorted(range(len(time_list)), key=lambda i: time_list[i])
    sorted_time_list = [time_list[i] for i in sorted_indices]
    sorted_array_list = [array_list[i] for i in sorted_indices]
    return sorted_time_list, sorted_array_list

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多