简体   繁体   English

排序numpy列表

[英]Sorting numpy lists

I am having troubles working with NumPy arrays as I am new to NumPy. 我不熟悉NumPy,因此在使用NumPy数组时遇到了麻烦。 I have a big input which I read with sys.stdin , which is consisted of lines with 2 values and a space between them, representing a point or two coordinates. 我用sys.stdin读取了一个很大的输入,该输入由具有2个值的线和它们之间的空格组成,表示一个点或两个坐标。 I then save it in a list which looks something like this: 然后,将其保存在如下所示的列表中:

np.array([[1, 3], [5, 6], [7, 2], [9, 9]])

I want to sort the list by their sums and then by their x-coordinate, but I am not sure how to do this. 我想按其总和然后按其X坐标对列表进行排序,但是我不确定如何执行此操作。

I am also not sure how would I add that sum as the third element of each sublist, in case I wanted to add it. 我也不确定如何将总和作为每个子列表的第三个元素,以防万一我想添加它。

Relying on python's built-in sorted is inefficient for numpy-arrays, especially when these are big. 对于numpy数组,依靠python的内置sorted效率低下,尤其是当它们很大时。 Try this instead: 尝试以下方法:

import numpy as np

l = np.array([[1, 3], [5, 6], [7, 2], [9, 9]])

ind = np.lexsort((l[:,0], l.sum(axis=1)))

sorted_l = l[ind]

ind will contain the indices of your original array, sorted by the two arrays given to lexsort . ind将包含原始数组的索引, lexsortlexsort的两个数组排序。 The last array is the primary sort column for lexsort . 最后一个数组是lexsort的主要排序列。 l[ind] selects these indices from your original array. l[ind]从原始数组中选择这些索引。

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

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