470,614 Members | 1,396 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,614 developers. It's quick & easy.

sorting list of tuples by second (third...) tuple item

Hi,

I'm not in the mailing list.
By Googling, I stepped into this an old post: (Thu Feb 14 20:40:08 CET 2002)
of Jeff Shannon:
http://mail.python.org/pipermail/pyt...ry/128438.html

<<<
def SortOnItem(mylist, index):
templist = [ (line[index], line) for line in mylist ]
templist.sort()
return [ line[1:] for line in templist ]

What this does is build a separate list containing a tuple of the
element that you want to sort on, and the entire line, sorts that
list (by the first element, of course), and then strips that first
element off ..
>>>
It seems to me that the tuples aren't sorted only by the first element but,
I suppose, other elements are also used if needed to discriminate.
In some cases I got some exceptions when an element of the tuple, other than
the first, didn't admit comparison.
In these cases I had to use an ad hoc comparison function.

Regards, Giovanni Toffoli

Feb 16 '07 #1
1 2747
Giovanni Toffoli a écrit :
Hi,

I'm not in the mailing list.
By Googling, I stepped into this an old post: (Thu Feb 14 20:40:08 CET
2002) of Jeff Shannon:
http://mail.python.org/pipermail/pyt...ry/128438.html

<<<
def SortOnItem(mylist, index):
templist = [ (line[index], line) for line in mylist ]
templist.sort()
return [ line[1:] for line in templist ]

What this does is build a separate list containing a tuple of the
element that you want to sort on, and the entire line, sorts that
list (by the first element, of course), and then strips that first
element off ..
It's the "decorate/sort/undecorate" pattern. You may also google for
"schwarzian transform"
>>>>

It seems to me that the tuples aren't sorted only by the first element
but, I suppose, other elements are also used if needed to discriminate.
Yes. When compared, tuples first compare on the first element, then on
the second etc...
In some cases I got some exceptions when an element of the tuple, other
than the first, didn't admit comparison.
In these cases I had to use an ad hoc comparison function.
Did you try the sorted() function ? Used with operator.itemgetter as the
'key' argument, it may do the trick.
Feb 16 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

39 posts views Thread by Erlend Fuglum | last post: by
4 posts views Thread by David Bear | last post: by
8 posts views Thread by Nickolay Kolev | last post: by
66 posts views Thread by Darren Dale | last post: by
14 posts views Thread by Richard | last post: by
8 posts views Thread by nidhog | last post: by
17 posts views Thread by John Salerno | last post: by
10 posts views Thread by rshepard | last post: by
16 posts views Thread by skip | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.