Sorting a Python List by Multiple Fields
When working with sorted lists, it can be necessary to sort by multiple criteria. This becomes important when there are ties in the first sort key, and you want to break them using a second key.
To sort a list by two fields in Python, you can use lambda functions with the sorted() function. This allows you to specify multiple sort keys in a single expression.
list1 = sorted(csv1, key=lambda x: (x[0], x[1]))
In this example, the list is sorted by the value in field 1, and then by the value in field 2. The lambda function takes the item as input and returns a tuple of the first field value and the second field value. The sorted() function then sorts the list based on the returned tuples.
You can also use this technique to sort by one field ascending and another field descending:
sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))
In this example, the list is sorted by the first field value, and then by the second field value in descending order (because of the negative sign). This can be useful when you want to sort by the highest values in the second field for each unique value in the first field.
The above is the detailed content of How Can I Sort a Python List by Multiple Fields?. For more information, please follow other related articles on the PHP Chinese website!