sorting list of tuples by second (third...) tuple item
kevin parks
kp87 at lycos.com
Fri Feb 15 01:38:38 EST 2002
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]
[['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, \
['i3', 17.0, 0.5, 101, 7, 6, 7, 0, 0, 0, -1, 0, 5, \
['i3', 25.5, 0.5, 101, 4, 3, 7, 0, 0, 0, 1, 0, 5, \
['i6', 2.0, 0.5, 85, 7, 4, 6, 0, 0, 0, -1, 0.02, 2, \
['i3', 13.5, 0.5, 101, 4, 3, 7, 0, 0, 0, 1, 0, 5, \
['i4', 5.5, 6.5996, 101, 7, 4, 5, 7, 4, 5, 1, 0, 50, 50, 6.5, 6.5,
0.08000002, \
['i9', 18.0, 6.0, 100, 1, 1, 3, 0, 0, 0, 0, 0, 5, \
['i2', 222.0, 16.0, 1.100001, 1.1699, 0.56995, 0.7800003, \
['i3', 26.5, 0.5, 101, 7, 6, 7, 0, 0, 0, -1, 0, 5, \
['i9', 16.0, 0.5, 50, 7, 4, 3, 0, 0, 0, 0, 0, 5, \
['i6', 1.0, 0.5, 85, 1, 1, 7, 0, 0, 0, -1, 0.02, 2, \
['i3', 28.0, 0.5, 101, 4, 3, 7, 0, 0, 0, 1, 0, 5, \
['i9', 24.0, 1.5, 50, 1, 1, 4, 0, 0, 0, 0, 0, 5, \
['i7', 0.5, 0.5, 101, 1, 1, 6, 0, 0, 0, 1, 0.02, 2, \
['i6', 0.5, 0.5, 85, 7, 4, 6, 0, 0, 0, -1, 0.02, 2, \
['i8', 81.5, 0.75, 101, 7, 4, 4, 0, 0, 0, 0, 0.02, 2, \
['i6', 1.5, 0.5, 85, 7, 6, 7, 0, 0, 0, -1, 0.02, 2, \
['i9', 14.5, 1.5, 50, 1, 1, 4, 0, 0, 0, 0, 0, 5, \
['i9', 17.0, 1.0, 50, 1, 1, 4, 0, 0, 0, 0, 0, 5, \
['i3', 29.0, 0.5, 101, 7, 6, 7, 0, 0, 0, -1, 0, 5, \
['i3', 12.0, 0.5, 101, 7, 6, 7, 0, 0, 0, -1, 0, 5, \
['i3', 16.0, 0.5, 101, 4, 3, 7, 0, 0, 0, 1, 0, 5, \
['i1', 0, 0, 18.715278000000001, \
['i3', 14.5, 0.5, 101, 7, 6, 7, 0, 0, 0, -1, 0, 5, \
['i2', 181.4001, 0.1000001, 0.62, 0.63, 1.100001, 1.1699]]
so you would want the above list to have all the i1 lines together and
all the lines that start i2 together and then all the lines that have
the same starting value sorted by their second value, so that the
above list would start to sort perhaps like this:
x = [['i1',0,0,18.715278], ['i2',181.4,0.1,0.62,0.63,1.10,1.17],
['i2',222.0,16.0,1.10,1.17,0.57,0.78],
['i3',12.000,0.500,101,7,6,7,0,0,0,-1,0,5],
['i3',13.500,0.500,101,4,3,7,0,0,0,1,0,5],
['i3',14.500,0.500,101,7,6,7,0,0,0,-1,0,5],
['i3',16.000,0.500,101,4,3,7,0,0,0,1,0,5],
['i3',17.000,0.500,101,7,6,7,0,0,0,-1,0,5],
['i3',24.000,0.500,101,7,6,7,0,0,0,-1,0,5],
['i3',25.500,0.500,101,4,3,7,0,0,0,1,0,5],
['i3',26.500,0.500,101,7,6,7,0,0,0,-1,0,5],
['i3',28.000,0.500,101,4,3,7,0,0,0,1,0,5],
.
.
.
? I have a stupid audio program that has a broken sort routine and
barfs if things are not presorted this way, even though it is supposed
to sort everything for you..
one odd thing to note is that the nested lists are not all the same
size.
inquiring minds want to know.
bets,
kevin
More information about the Python-list
mailing list