How to sort a list of tuples

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Fri Nov 19 12:57:29 CET 2004


On Fri, 19 Nov 2004 18:22:45 +0800, rumours say that Valkyrie
<valkyrie at 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_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



More information about the Python-list mailing list