0

I have a list of tuples. Each tuple consists of another tuple and an index. I want to sort the list depending on the difference between the values of the inner tuple. Or, in another notation:

[((float, float), int), ...]

The two floats are what I want to use in the sort key.

I wrote this:

from math import fabs

def sort_for_avg(probabilities):  # 'probabilites' is a list of float-pairs
    return sorted(zip(probabilites, range(len(probabilites))),
                  key=lambda entry: fabs(entry[0][0]-entry[0][1]))

I tried working with itemgetter, but I didn't get the hang of it for something that isn't just sorting with a simple lookup. The 'sorted' list goes all over the place, seemingly randomly.

As the probability table can get quite big, I wanted my solution to not copy any values, which is why this is such a complicated one-liner. If someone knew how to do the same in a couple of lines with generators, I would be happy, too.

2
  • Could you provide some inputs and expected and actual outputs? Have a look at stackoverflow.com/help/mcve. It would be helpful if your "another notation" was Python's, e.g. [((float, float), int), ...] Commented Feb 2, 2015 at 16:36
  • Can not reproduce. After fixing the typos, this seems to work okay. Could the problem be somewhere else? Can you provide some test data? Is your result sorted randomly, or not sorted at all, i.e. is the index row still ordered? In this case, you probably forgot to assign the result back to the variable. Commented Feb 2, 2015 at 16:36

1 Answer 1

3

Example data:

probabilities = [((1.0,2.0),3),((3.0,1.0),1),((0.5,1.0),2)]

To sort in place:

probabilities.sort(key=lambda x: abs(x[0][0]-x[0][1]))

Output:

>>> probabilities
[((0.5, 1.0), 2), ((1.0, 2.0), 3), ((3.0, 1.0), 1)]

Or to return a new sorted list:

sorted_probabilities = sorted(probabilities, key=lambda x: abs(x[0][0]-x[0][1]))

Output:

>>> sorted_probabilities
[((0.5, 1.0), 2), ((1.0, 2.0), 3), ((3.0, 1.0), 1)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this wraps it up nicely, everything working as expected now.

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.