sorting list of tuples by second (third...) tuple item
Paul Rubin
phr-n2002a at nightsong.com
Fri Feb 15 01:44:05 EST 2002
kp87 at lycos.com (kevin parks) writes:
> How would you sort something based on 2 criteria. Say you have a list
> of lists (i hate tuples). first thing you want is everything sorted by
> the first value and then everything that has the same value for [0]
> then sorted by [1]
# try this:
yourlist = [['i3', 24.0, 0.5, 101, 7, 6, 7, 0, 0, 0, -1, 0, 5], \
['i8', 82.25, 0.75, 101, 7, 6, 5, 0, 0, 0, 0, 0.02, 2], \
['i9', 9, 0, 255], \
['i8', 83.0, 1.0, 101, 1, 1, 5, 0, 0, 0, 0, 0.02, 2]]
def compare_lists(x,y):
a = cmp(x[0],y[0])
if a: return a
return cmp(x[1],y[1])
yourlist.sort(compare_lists)
More information about the Python-list
mailing list