Sorting of list containing tuples

R

Ronny Mandal

Hi!

Assume we have a list l, containing tuples t1,t2...

i.e. l = [(2,3),(3,2),(6,5)]

And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]


Any ideas of how to accomplish this?


Thanks,

Ronny Mandal
 
P

Paul Rubin

Ronny Mandal said:
And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]

sorted(l, key = lambda a: -a[1])
 
R

Ronny Mandal

Uhm, thanks. (I've used lambda-sort earlier, but quite forgot......)
:)

Ronny Mandal said:
And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]

sorted(l, key = lambda a: -a[1])
 
D

Dave Hansen

Hi!

Assume we have a list l, containing tuples t1,t2...

i.e. l = [(2,3),(3,2),(6,5)]

And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]


Any ideas of how to accomplish this?


Thanks,

Ronny Mandal
c1 = t1[1]
c2 = t2[1]
if c1 > c2: return 1
if c2 > c1: return -1
return 0
l [(2, 3), (3, 2), (6, 5)]
l.sort(cmp=my_cmp, reverse = True)
l
[(6, 5), (2, 3), (3, 2)]

HTH,
-=Dave
 
W

Wojciech =?iso-8859-2?Q?Mu=B3a?=

Ronny said:
Assume we have a list l, containing tuples t1,t2...

i.e. l = [(2,3),(3,2),(6,5)]

And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]


Any ideas of how to accomplish this?

def cmpfun(a,b):
return cmp(b[1],a[1])

l.sort(cmpfun)
 
C

Christoph Haas

Ronny Mandal said:
And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]

sorted(l, key = lambda a: -a[1])

Or in Python <2.4:

l.sort(lambda x,y: x[1]-y[1])

(Although that's not technically perfect. Sort expect a function that
returns -1, 0 or 1. Here we get positive integers and negative
integers. YMMV.)

Kindly
Christoph
 
C

Christoph Haas

Ronny Mandal said:
And now I want to sort l reverse by the second element in the tuple,
i.e the result should ideally be:

l = [(6,5),(2,3),(3,2)]

sorted(l, key = lambda a: -a[1])

Or in Python <2.4:

l.sort(lambda x,y: x[1]-y[1])

(Although that's not technically perfect. Sort expect a function that
returns -1, 0 or 1. Here we get positive integers and negative
integers. YMMV.)

Crap... why do I always forget about cmp()? :)

This should be it:

l.sort(lambda x,y: cmp(x[1],y[1]))

Kindly
Christoph
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top