Home > Article > Backend Development > How Can I Sort a Python List by Multiple Fields Using Lambda Functions?
Sorting a Python List by Multiple Fields
You have a Python list created from a sorted CSV file using the itemgetter operator. While the list is already sorted by the value in the second field, you want to enhance the sorting to include the first field as well.
To achieve this, you can leverage lambda functions. They allow you to define a custom sorting key that considers multiple criteria.
The following code provides a solution:
sorted_list = sorted(list1, key=lambda x: (x[0], x[1]))
Here's how it works:
By using lambda functions, you can easily define complex sorting criteria and sort your Python lists according to your specific requirements.
The above is the detailed content of How Can I Sort a Python List by Multiple Fields Using Lambda Functions?. For more information, please follow other related articles on the PHP Chinese website!