473,508 Members | 2,104 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to sort a list of tuples

I have a list of tuples, and one of the fields in the tuple is score. So how can
I sort the list by the score?

Thanks in advance
Jul 18 '05 #1
5 4538
On Fri, 2004-11-19 at 18:22, Valkyrie wrote:
I have a list of tuples, and one of the fields in the tuple is score. So how can
I sort the list by the score?


Assuming the score field is index 1 of each tuple:

def cmp(a,b):
if a[1] < b[1]:
return -1
elif a[1] > b[1]:
return 1
else:
return 0

my_tuple_list.sort(cmp)

(technically the elifs could be ifs, and the final else could be omitted
in favour of just 'return 0', but for clarity the above is IMO best).

see 'help(list.sort)' for more information.

To whoever added this fantastic feature, thanks and more thanks. It's
saved me so much work at times that it's just crazy.

--
Craig Ringer

Jul 18 '05 #2
On Fri, 19 Nov 2004 18:22:45 +0800
Valkyrie <va******@cuhk.edu.hk> wrote:
I have a list of tuples, and one of the fields in the tuple is score. So how can
I sort the list by the score?


In 2.4 you can use key argument of sort method:
l = [('a', 2), ('c', 3), ('b', 1)]
l.sort(key=lambda i: i[1])
l [('b', 1), ('a', 2), ('c', 3)]

otherwise pass comparison function: l = [('a', 2), ('c', 3), ('b', 1)]
l.sort(lambda i1, i2: cmp(i1[1], i2[0]))
l

[('b', 1), ('c', 3), ('a', 2)]

--
Denis S. Otkidach
http://www.python.ru/ [ru]
Jul 18 '05 #3
Thank you all, it's perfectly fine now :)

Valkyrie wrote:
I have a list of tuples, and one of the fields in the tuple is score. So how can
I sort the list by the score?

Thanks in advance

Jul 18 '05 #4
On Fri, 19 Nov 2004 18:22:45 +0800, rumours say that Valkyrie
<va******@cuhk.edu.hk> might have written:
I have a list of tuples, and one of the fields in the tuple is score. So how can
I sort the list by the score?


Python 2.4:

def sort_tuple_list(tuple_list, index_of_score):
tuple_list.sort(key=operator.itemgetter(index_of_s core))

If for example your tuple_list is of the format (v1, score, v3, v4),
then you sort by

sort_tuple_list(tuple_list, 1)

1 is the second item (0 is the first).

actual example:
import operator
tuple_list= [ ('chris', 15),
('pers6', 3),
('pers1', 56),
] sort_tuple_list(tuple_list, 1)
tuple_list

[('pers6', 3), ('chris', 15), ('pers1', 56)]
--
TZOTZIOY, I speak England very best,
"Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek
Jul 18 '05 #5
Valkyrie wrote:
I have a list of tuples, and one of the fields in the tuple is score. So how can
I sort the list by the score?

Thanks in advance


Others have showed the possibility of a comparison function, but often
it's faster to use the decorate-sort-undecorate pattern:

def sort_on(list_to_sort, field_num):
templist = [ (item[field_num], item) for item in list_to_sort ]
templist.sort()
return [ item[1] for item in templist ]

Note that I'm creating a new list, leaving the original list unsorted.
You can easily rebind the original name to the sorted list if needed --

mylist = sort_on(mylist, 3)

I believe that using the key=... in 2.4 is faster than this DSU pattern,
but DSU is typically faster than using a cmp() function/lambda.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3407
by: Ken R. | last post by:
Hello all, I am relatively new to python but I am having an issue with custom sort functions.. I am trying to sort a list of lists or tuples with arbitrary ascending or descending sorts. For...
3
9328
by: Mike Zupan | last post by:
I have a list that includes files and directories ie: list = I want to sort it so it looks like this I'm just wondering if there is an easy way to do this
3
2105
by: Thorsten Kampe | last post by:
I found out that I am rarely using tuples and almost always lists because of the more flexible usability of lists (methods, etc.) To my knowledge, the only fundamental difference between tuples...
3
1617
by: Brian McGonigle | last post by:
I'm a Perl programmer learning Python (up to chapter 7 in Learning Python, so go easy on me :-) and I find that I look to do things in Python the way I would do them in Perl. In Perl functions and...
2
2001
by: Thomas Philips | last post by:
I recently had the need to sort a large number of lists of lists, and wondered if an improvement to the Decorate-Sort-Undecorate idiom is in the works. Ideally, I would like to sort the list of...
1
2272
by: Kamilche | last post by:
I've written a generic sort routine that will sort dictionaries, lists, or tuples, either by a specified key or by value. Comments welcome! import types def sort(container, key = None,...
18
6178
by: googleboy | last post by:
I didn't think this would be as difficult as it now seems to me. I am reading in a csv file that documents a bunch of different info on about 200 books, such as title, author, publisher, isbn,...
11
16770
by: Noah | last post by:
I have a list of tuples I want to reverse the order of the elements inside the tuples. I know I could do this long-form: q = y = for i in y: t=list(t)
10
5133
by: rshepard | last post by:
While working with lists of tuples is probably very common, none of my five Python books or a Google search tell me how to refer to specific items in each tuple. I find references to sorting a list...
0
7226
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7388
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7049
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
4709
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3199
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3186
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1561
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
767
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
422
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.