How to sort a two-dimensional list in Python

WBOY
Release: 2024-03-01 13:31:02
forward
415 people have browsed it

How to sort a two-dimensional list in Python

In python, you can use the sorted() function to sort the two-dimensional list. You can specify the sorting rules by passing a lambda function as the key parameter.

The following is an example of sorting a two-dimensional list in ascending order by the first element of each sublist:

my_list = [[3, 2], [1, 4], [5, 6], [0, 2]]
sorted_list = sorted(my_list, key=lambda x: x[0])
print(sorted_list)
Copy after login

Output result:

[[0, 2], [1, 4], [3, 2], [5, 6]]
Copy after login

You can also pass the reverse=True parameter to the sorted() function to sort in descending order. For example, here is an example that sorts in descending order by the second element of each sublist:

my_list = [[3, 2], [1, 4], [5, 6], [0, 2]]
sorted_list = sorted(my_list, key=lambda x: x[1], reverse=True)
print(sorted_list)
Copy after login

Output result:

[[5, 6], [1, 4], [3, 2], [0, 2]]
Copy after login

The above is the detailed content of How to sort a two-dimensional list in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:lsjlt.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!