4

First, this is the code that does not work:

ls = [(1.0,np.array([3.0, 4.0])), (1.0,np.array([3.0, 4.1])), (3.0,np.array([2.0, 1.0]))]
ls.sort()

As you can see, I have a list of tuples (ls). The first element of each tuple is a float number. I try to sort the list by ls.sort(). In most of the cases it works well. However, sometimes (like in the example above) I have tuples with the same value of their first element. In this case the python try to use the second element of the tuple to sort out the tuples and it does not work because on the second place in the tuple I have numpy array.

How can I sort my list by ignoring the second elements of the tuples? If the first element is the same, I do not care about the ordering (it can be original ordering, or random).

2 Answers 2

3

Either tell python to sort only on the first item

sorted(ls, key=lambda t: t[0])

Or convert the whole thing to a structured numpy array and ask numpy to sort it

ls_arr = np.array(ls, dtype=[('my_val', float), ('my_arr', float, 2)])
ls_arr.sort()

This second option only works if the arrays are always the same length.

Sign up to request clarification or add additional context in comments.

Comments

2

Probably using the key parameter. Is this what you want?

import numpy as np
ls = [(1.0,np.array([3.0, 4.0])), (1.0,np.array([3.0, 4.1])), (3.0,np.array([2.0, 1.0]))]
ls.sort(key=lambda x: x[0])

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.