sorting list of tuples by second (third...) tuple item
Just van Rossum
just at xs4all.nl
Fri Feb 15 03:31:19 EST 2002
In article <7xzo2bnt1m.fsf at ruckus.brouhaha.com>,
Paul Rubin <phr-n2002a at nightsong.com> wrote:
> 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)
Nah, just do this:
yourlist.sort()
Just
More information about the Python-list
mailing list