简体   繁体   中英

Sort lists in a nested list based on the argsort of the 0th list

What's the neatest way to sort a nest of list based on the first list in the list?

before sort

>>> list_of_things = [[100,300,200],[t,u,v]]

after sort

>>> [[100,200,300],[t,v,u]]

So far using search I've located an index I can use to sort

>>> import numpy as np
>>> sort_index=np.argsort(list_of_things[0]) 

But I haven't found a pythonic way to index both sublists on sort_index.

Any thoughts? Thank you!

print(arr) 
array([['100', '300', '200'],
       ['t', 'u', 'v']],
      dtype='<U21')

First, argsort the 0 th list:

idx = np.argsort(arr[0])

print(idx)
array([0, 2, 1])

Now, just use numpy indexing :

arr = arr[:, idx]

print(arr)
array([['100', '200', '300'],
       ['t', 'v', 'u']],
      dtype='<U21')

Try a tool from more_itertools , a third-party library that sorts iterables in parallel.

First install the library:

> pip install more_itertools

Code

from more_itertools import sort_together


iterables = [[100, 300, 200], ["t", "u", "v"]]
sort_together(iterables)
# [(100, 200, 300), ('t', 'v', 'u')]

All iterables are sorted by the a 0-th index by default. This sorting priority can be adjusted by the key_list parameter.

See more_itertools docs for details.

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