Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Python list by two fields

Tags:

python

sorting

I have the following list created from a sorted csv

list1 = sorted(csv1, key=operator.itemgetter(1))

I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this?

like image 501
half full Avatar asked Mar 06 '11 19:03

half full


People also ask

How do you sort a list by two columns in Python?

To sort a Python list by two fields, we can use the sorted function. to call sorted to return the list items sorted by calling it with the key argument set to a lamnda function that has a tuple of values to sort by. We sort x[1] in descending order since we have a minus sign before the value.

How do you sort a list by second element?

Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.


2 Answers

No need to import anything when using lambda functions.
The following sorts list by the first element, then by the second element. You can also sort by one field ascending and another descending for example:

sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))
like image 139
jaap Avatar answered Oct 05 '22 10:10

jaap


like this:

import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
like image 25
mouad Avatar answered Oct 05 '22 09:10

mouad