Sorting a Python List by Multiple Fields
Sorting a Python list by a single field is a common task, but what if you need to sort by multiple fields?
Consider the following list created from a sorted CSV file:
list1 = sorted(csv1, key=operator.itemgetter(1))
This sorts the list by the second field. However, what if you want to sort first by the first field and then by the second field?
The solution is to use a lambda function as the key argument to the sorted() function. A lambda function is an anonymous function that can be used to define a simple sorting criterion. In this case, the lambda function takes a single argument, which represents an element in the list, and returns a tuple containing the two fields that you want to sort by.
For instance, to sort the list by the first and second fields, you can use the following lambda function:
sorted_list = sorted(list1, key=lambda x: (x[0], x[1]))
This lambda function returns a tuple containing the first and second fields of the list element. The list is then sorted by this tuple, which results in the list being sorted first by the first field and then by the second field.
You can also use lambda functions to sort by one field ascending and another descending. For example, to sort the list by the first field ascending and the second field descending, you can use the following lambda function:
sorted_list = sorted(list1, key=lambda x: (x[0], -x[1]))
This lambda function returns a tuple containing the first field of the list element and the negative of the second field. The list is then sorted by this tuple, which results in the list being sorted by the first field ascending and the second field descending.
The above is the detailed content of How to Sort a Python List by Multiple Fields?. For more information, please follow other related articles on the PHP Chinese website!