python 判断矩阵中每行非零个数的方法
作者:野牛程序员:2023-12-05 16:40:21python阅读 2752
python 判断矩阵中每行非零个数的方法
使用Python,可以使用NumPy库来判断矩阵中每行非零元素的个数。以下是一个简单的示例代码:
import numpy as np def count_nonzero_elements(matrix): # 计算每行非零元素的个数 nonzero_counts = np.count_nonzero(matrix, axis=1) return nonzero_counts # 例子 matrix = np.array([[1, 0, 2, 0], [0, 0, 0, 0], [3, 4, 0, 0], [0, 0, 0, 5]]) result = count_nonzero_elements(matrix) print(result)
这个例子中,count_nonzero
函数用于沿着指定轴计算非零元素的个数。axis=1
表示沿着每行进行计算。在这个例子中,result
将包含每行非零元素的个数。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
