Home >Backend Development >Python Tutorial >How to sort a two-dimensional list in Python

How to sort a two-dimensional list in Python

WBOY
WBOYforward
2024-03-01 13:31:02572browse

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)

Output result:

[[0, 2], [1, 4], [3, 2], [5, 6]]

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)

Output result:

[[5, 6], [1, 4], [3, 2], [0, 2]]

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!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete