Python equivalent for php usort ()?

My data structure is a list of tuples in Python, and I would like to be able to sort the list items by the value contained in their tuples. In PHP, I usually created my own sort function using the usort () function. Is there an equivalent in Python that I could use?

+4
source share
2 answers

Give the sort() a key method:

 >>> my_list = [(1, 2), (3, 4), (2, 1), (3, 2)] >>> my_list.sort(key=lambda x: x[1]) >>> my_list [(2, 1), (1, 2), (3, 2), (3, 4)] >>> 

If you need to get a sorted list, instead of sorting in place, use the builtin on sorted()

 >>> sorted(my_list, key=lambda x: x[1]) [(2, 1), (1, 2), (3, 2), (3, 4)] 
+7
source

There is no predefined function to perform this function, but it can be done quite easily using the functions of the operator module as a key function for sorting. As the sample code shows, you can use

 from operator import itemgetter tuple_list.sort(key=itemgetter(1)) 

This sorts by index 1 elements in tuples.

+3
source

All Articles