简体   繁体   中英

Sort a list of arrays using the sort of other array python

I have two lists : a list of 2D-arrays and the time it was generated, which is an integer. They are of length N and both "equally disordered". So by using the indices to order the list 'time' I can order the list of 2D-arrays.

I would like to do something like:

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

Another option would be to leave it as a list:

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

By iterating np.argsort(time) I could sort my disordered_list but I would like to know if there is a better option for this or which are the best.

Thanks

Create an index array and sort it based on time_list's value. Then use those indices to construct sorted versions of both arrays.

Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM