How to Sort a Python List by Multiple Fields?

Barbara Streisand
Release: 2024-11-23 18:23:10
Original
643 people have browsed it

How to Sort a Python List by Multiple Fields?

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))
Copy after login

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]))
Copy after login

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]))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template