Example
class Solution:
def solve(self, matrix):
R = len(matrix)
C = len(matrix[0])
res = [[0] * C for _ in range(R)]
for col in range(C):
values = [r[col] for r in matrix]
values.sort(reverse=True)
for row in range(R):
res[row][col] = values.pop()
return res
ob = Solution()
matrix = [[11, 21, 31],[6, 6, 4],[1, 11, 8]]
print(ob.solve(matrix))
Input
[[11, 21, 31], [6, 6, 4], [1, 11, 8]]
Output
[[1, 6, 4],[6, 11, 8],[11, 21, 31]]
https://www.tutorialspoint.com/column-sort-of-a-matrix-in-python
python 按二维数组的某行或列排序 (numpy lexsort)
lexsort支持对数组按指定行或列的顺序排序;是间接排序,lexsort不修改原数组,返回索引。
(对应lexsort 一维数组的是argsort a.argsort()这么使用就可以;argsort也不修改原数组, 返回索引)
默认按最后一行元素有小到大排序, 返回最后一行元素排序后索引所在位置。
设数组a, 返回的索引ind,ind返回的是一维数组
对于一维数组, a[ind]就是排序后的数组。
对于二维数组下面会详细举例。
import numpy as np
>>> a
array([[ 2, 7, 4, 2],
[35, 9, 1, 5],
[22, 12, 3, 2]])
按最后一列顺序排序
>>> a[np.lexsort(a.T)]
array([[22, 12, 3, 2],
[ 2, 7, 4, 2],
[35, 9, 1, 5]])
按最后一列逆序排序
>>>a[np.lexsort(-a.T)]
array([[35, 9, 1, 5],
[ 2, 7, 4, 2],
[22, 12, 3, 2]])
按第一列顺序排序
>>> a[np.lexsort(a[:,::-1].T)]
array([[ 2, 7, 4, 2],
[22, 12, 3, 2],
[35, 9, 1, 5]])
按最后一行顺序排序
>>> a.T[np.lexsort(a)].T
array([[ 2, 4, 7, 2],
[ 5, 1, 9, 35],
[ 2, 3, 12, 22]])
按第一行顺序排序
>>> a.T[np.lexsort(a[::-1,:])].T
array([[ 2, 2, 4, 7],
[ 5, 35, 1, 9],
[ 2, 22, 3, 12]])
Example
import numpy as np
a= [[ 2, 7, 4, 2],
[35, 9, 1, 5],
[22, 12, 3, 2]]
a = np.array(a)
print (a[np.lexsort(-a.T)])
How to Sort Array in Python
https://www.askpython.com/python/array/sort-array-python
Sorting Arrays
https://jakevdp.github.io/PythonDataScienceHandbook/02.08-sorting.html
Sorting HOW TO
https://docs.python.org/3/howto/sorting.html