List of tuples

Richard Chamberlain richard_chamberlain at ntlworld.com
Sat Aug 12 08:46:42 EDT 2000


Hi Chris,

That depends on the behaviour you want. For instance:

x=[('spam',234,32),('spam',233,32),('eggs',34,10),('Spam',235,32)]
x.sort()

The problem with that is that ('Spam',235,32) would be the first in the
list, plus it would use the second item in the tuple if the first
doesn't differentiate. Having said that your function would also put
Spam first as well, so if that's not the behaviour you want then simply
convert them to all lower or uppercase before comparing them.

If you can live with sorts behaviour it would be faster.

Richard



CHRIS wrote:
> 
> lets say there's a list of tupples:
> 
> x = [('foo', 234, 32), ('bar', 213, 123)];
> 
> If I want to sort the list by the first element of the tuple should I
> make a custom compare funciton:
> def statcmp(t1, t2):
>   if t1[0] < t2[0]:
>     return 1;
>   elif t1[0] == t2[0]:
>     return 0;
>   else:
>     return -1;
> 
> x.sort(statcmp);
> 
> Or just sort:
> x.sort();
> 
> Thanks.



More information about the Python-list mailing list