[Tutor] Sorting ranges

Jeff Shannon jeff@ccvcorp.com
Wed, 05 Sep 2001 09:24:25 -0700


> does anyone know how to sort ranges in ascending order? Eg.

....

How are you storing your ranges, and how do you want them sorted?  If you're storing
them as a tuple of (start,end), or as a list of either [start,end] or full range
(i.e., the result of range(start,end) ), then you should be able to put all of them in
a list sort that--list.sort() will sort by the value of the first item.  In other
words,

>>> myranges = [ (780,1014), (771,1014), (29,214), (226,426) ]
>>> myranges.sort()
>>> print myranges
[(29, 214), (226, 426), (771, 1014), (780, 1014)]
>>> myranges = [ range(780,1014), range(771,1014), range(29,214), range(226,426) ]
>>> myranges.sort()
>>> for r in myranges: print r[0], r[-1]
...
29 213
226 425
771 1013
780 1013
>>>

Jeff Shannon
Technician/Programmer
Credit International