Home >Backend Development >Python Tutorial >How to sort a two-dimensional array by columns in Python

How to sort a two-dimensional array by columns in Python

WBOY
WBOYforward
2024-03-01 14:49:30579browse

How to sort a two-dimensional array by columns in Python

In python, you can use the sorted function and the lambda function to sort the two-dimensional array by columns. Here is a sample code:

# 二维数组
matrix = [[5, 2, 3],
[1, 7, 6],
[4, 8, 9]]

# 定义按列排序的函数
def sort_by_column(arr, column):
return sorted(arr, key=lambda x: x[column])

# 按第一列排序
sorted_matrix = sort_by_column(matrix, 0)
print(sorted_matrix)

# 输出结果:[[1, 7, 6], [4, 8, 9], [5, 2, 3]]

In the above code, we define a sort_by_column function, which accepts a two-dimensional array and a column index as parameters, and then uses the sorted function to sort the two-dimensional array. The lambda function is used to specify the sorting key, that is, to sort according to the specified column of each subarray. Finally, we call the sort_by_column function, passing in the two-dimensional array and column index 0, that is, sorting by the first column.

The above is the detailed content of How to sort a two-dimensional array by columns 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