Arne
Arne

Reputation: 20157

Sorting a complex datastructure

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.

Upvotes: 0

Views: 53

Answers (1)

Imran
Imran

Reputation: 13458

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

Upvotes: 3

Related Questions