I want to sort the sub-arrays in a NumPy array that I have according to their length.
For example my array is
myArray = [[1,2,3,4,5,6,7],
[8,9,10,11],
[12],
[13],
[14,15,16,17,18,19,20,21,22,23,24]]
and I want to sort them as
myArray = [[14,15,16,17,18,19,20,21,22,23,24],
[1,2,3,4,5,6,7],
[8,9,10,11],
[12],
[13]]
Is there any possible way to doing this?
The content of my sub-arrays should not change.
CodePudding user response:
That is a simple list of lists - to do what you need:
sorted(myArray, key=lambda x: -len(x))
FOLLOW UP: if you have a numpy
array, as follows:
myArray = np.array([np.array(x) for x in [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11], [12], [13], [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]]])
You can obtain a similar result:
np.array([y for x,y in sorted([(-len(x), x) for x in myArray])])
OUTPUT:
array([array([14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]),
array([1, 2, 3, 4, 5, 6, 7]), array([ 8, 9, 10, 11]), array([12]),
array([13])], dtype=object)