Reputation: 1781
Suppose I have the following lists
['foo', '333', 32.3]
['bar', 4.0]
['baz', '555', '2232', -1.9]
I want to be able to sort this via the last element (float)
['baz', '555', '2232', -1.9]
['bar', 4.0]
['foo', '333', 32.3]
In ascending order
count_array = np.array([('foo', '333', 32.3),('bar', 4.0),('baz', '555', '2232', -1.9)], dtype = np.object)
idx = np.argsort(count_array[:, 1])
print(count_array[idx])
I want to be able to sort a 2-D list by comparing its last element. This code ONLY works if the sublists are the same length.
How can I get it to work for variable length sublists?
The problem is this line idx = np.argsort(count_array[:, 1])
Upvotes: 2
Views: 854
Reputation: 86188
I would just use plain lists
here, when you create a numpy.array
with sub-lists of different lengths (or different data types in your array
) you get an array
of type object
, which lacks many useful numpy
features and is rarely a good idea to implement.
x = [['foo', '333', 32.3],
['bar', 4.0],
['baz', '555', '2232', -1.9]]
result = sorted(x, key=lambda k : k[-1], reverse=True)
Result:
>>> result
[['foo', '333', 32.3], ['bar', 4.0], ['baz', '555', '2232', -1.9]]
Upvotes: 2