dhaliman
dhaliman

Reputation: 1630

How to sort a list containing namedtuples based on the difference between attributes?

Segment = namedtuple('Segment', 'start end')
segments = [Segment(start=9, end=1), Segment(start=1, end=3), Segment(start=2, end=5), Segment(start=3, end=6)]

I tried the following code to sort the list:

sorted(segments, key = lambda s: s.end - s.start)

But this doesn't work. How can I do this?

Expected output:

[Segment(start=3, end=6), Segment(start=2, end=5), Segment(start=1, end=3), Segment(start=9, end=1)]

Upvotes: 3

Views: 318

Answers (1)

Sede
Sede

Reputation: 61253

You need to specify that you want the "sequence" where end < start or end - start < 0 first, also in case there are many segments that match that criteria, priority should be given to "sequence" with highest end value.

>>> from collections import namedtuple
>>> Segment = namedtuple('Segment', 'start end')
>>> segments = [Segment(start=9, end=1), Segment(start=1, end=3), Segment(start=2, end=5), Segment(start=3, end=6)]
>>> sorted(segments, key=lambda s: (s.end < s.start, -s.end))
[Segment(start=3, end=6), Segment(start=2, end=5), Segment(start=1, end=3), Segment(start=9, end=1)]

Upvotes: 2

Related Questions