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

WBOY
Release: 2024-03-01 14:49:30
forward
484 people have browsed it

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

Inpython, you can use the sorted function and the lambda function tosortthe two-dimensionalarrayby 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]]
Copy after login

In the above code, we define a sort_by_column function, which accepts a two-dimensional array and a columnindexas 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!

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
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!