Reputation: 939
rangeList = [range(15, 20), range(7, 10), range(11, 14)]
How do I sort the rangeList
, so that the resulting list look like below, Sorting based on the start value of the range ?
sortedRangeList = [range(7, 10), range(11, 14), range(15, 20)]
Upvotes: 1
Views: 2230
Reputation: 4009
If you want to save memory usage and perform an "In Place" sorting:
rangeList.sort(key=lambda rng: rng[0])
print(rangeList)
Output:
[range(7, 10), range(11, 14), range(15, 20)]
Otherwise, if you do not care about memory optimization, you can just use sorted:
sorted_ranges = sorted(rangeList, key=lambda rng: rng[0])
Upvotes: 0
Reputation: 88285
You could sort
based on the start
attribute of each range
:
sorted(rangeList, key=lambda r: r.start)
# [range(7, 10), range(11, 14), range(15, 20)]
By applying the above transformation function in the key
parameter, essentially sorted
will be ordering the list based on the following result:
[r.start for r in rangeList]
# [15, 7, 11]
Upvotes: 7