简体   繁体   English

根据数组对矩阵的行进行排序

[英]Sort rows of matrix based on array

My code try to sort a matrix based on an array, firts i try to sort the array from lowest to highest, the number of elements inside array are directly proportional to the number of rows in the matrix, so when i do bubblesort of the array, i want the same bubblesort in the matrix.我的代码尝试根据数组对矩阵进行排序,首先我尝试从最低到最高对数组进行排序,数组内的元素数与矩阵中的行数成正比,所以当我对数组进行冒泡排序时,我想在矩阵中使用相同的冒泡排序。

The code sort correctly the array, but the matrix is a mess.代码正确排序数组,但矩阵是一团糟。

matriz = np.array(([4, 1, 6, 9], [1, 3, 0, 2], [1, 0, 0, 2], [1, 1, 4, 5], [2, 1, 4, 1]))
for i in range(len(matrix)):
    n = int(len(matrix[i]))
    for j in range(n):
        average[i] += (matrix[i][j]/n)

print(average)
for a in range(len(average)-1):
    for b in range(a+1, len(average)):
        if average[a] > average[b]:
            aux = average[a]
            average[a] = average[b]
            average[b] = aux
            auxMatrix = matrix[a]
            matrix[a] = matrix[b]
            matrix[b] = auxMatrix

print(average)
print(matrix)

结果

If you are using numpy you might as well use its efficient functions:如果您使用的是 numpy 您不妨使用它的高效功能:

sorted_matrix = matrix[np.argsort(matrix.mean(axis=1))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM