473,651 Members | 2,765 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 4550
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.s ort(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=lamb da 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.i temgetter(index _of_score))

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
3416
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 example given a list of tuples ('firstname','lastname','age') I want to be able to sort lastname descending, firstname ascending and age ascending... I wrote a custom function generator to generate a sort function based
3
9337
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
2112
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 and lists is that tuples are immutable, so if this is correct, than list are a superset of tuples, meaning lists can do everything tuples can do and more. Is there any advantage for using tuples? Are they "faster"? Consume less memory? When is...
3
1619
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 methods usually only return and undefined value in the event of an error, make an endless number of compound statements possible. Is there a version of sort() I could import from somewhere that returns a reference to the object on which it was...
2
2005
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 lists (or tuples) in place by using a simple variant of the current idiom, i.e. list_of_lists.sort(*columns) where *columns is a tuple that specifies the column order for the sort. If *columns is left blank, the sort ought to work as it does...
1
2280
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, ascending = True): ' Sort lists or dictionaries by the specified key' t = type(container)
18
6197
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, date and several other bits of info too. I can do a simple sort over the first field (title as it turns out), and that is fine as far as it gets:
11
16785
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
5144
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 of tuples, but not extracting tuples based on their content. In my case, I have a list of 9 tuples. Each tuple has 30 items. The first two items are 3-character strings, the remaining 28 itmes are floats. I want to create a new list from...
0
8357
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8277
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8803
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8700
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8465
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7298
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4285
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2701
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 we have to send another system
2
1588
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.