简体   繁体   English

根据第0个列表的argsort对嵌套列表中的列表进行排序

[英]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. 但是我还没有找到一种在sort_index上为两个子列表建立索引的pythonic方法。

Any thoughts? 有什么想法吗? Thank you! 谢谢!

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

First, argsort the 0 th list: 首先, argsort第0 列表进行argsort

idx = np.argsort(arr[0])

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

Now, just use numpy indexing : 现在,只需使用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. 尝试使用来自more_itertools的工具,该工具是more_itertools可迭代对象进行并行排序的第三方库。

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. 默认情况下,所有可迭代项均按第0个索引排序。 This sorting priority can be adjusted by the key_list parameter. 可以通过key_list参数调整此排序优先级。

See more_itertools docs for details. 有关more_itertools信息,请参见more_itertools文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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