2

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])

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.