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?
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.
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.
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 this:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With