Reputation: 791
I am having troubles working with NumPy arrays as I am new to 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. 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.
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.
Upvotes: 2
Views: 120
Reputation: 5433
Relying on python's built-in sorted
is inefficient for numpy-arrays, especially when these are big. 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
. The last array is the primary sort column for lexsort
. l[ind]
selects these indices from your original array.
Upvotes: 3