对矩阵的列和行进行排序

时间:2014-04-17 22:26:38

标签: python sorting matrix line

我在Python中编写了用于输入矩阵的代码:

matrix = []
while True:
    line = input()
    if not line: break
    values = line.split()
    row = [int(value) for value in values]
    matrix.append(row)

例如,结果矩阵将是

[[9, 2, 4],
 [7, 8, 0]]

我想知道是否有办法对它的行和列进行排序?例如,对第一行进行排序会产生[2, 4, 9],对第一列进行排序会产生[7, 9]

2 个答案:

答案 0 :(得分:0)

def sortColumn(matrix, column):
    tempCol = [row[column] for row in matrix]
    #The above generator equals to
    #tempCol = []
    #for row in matrix:
    #    tempCol.append(row[column])
    tempCol.sort()
    i = 0
    for row in matrix:
        row[colum] = tempCol[i]
        i += 1

def sortRow(matrix, row):
    matrix[row].sort()

现在,如果要对矩阵的列进行排序,请执行

#Doesn't matter which row, all should have the same length
for column in range(0, len(matrix[0]): 
    sortColumn(matrix, column)

对于行,它会更简单,我会去

for row in matrix:
    row.sort()

答案 1 :(得分:0)

matrix = []
while True:
    line = input()
    if not line: break
    values = line.split()
    row = [int(value) for value in values]
    matrix.append(row.sort())

然后只需按列打印排序:

sorted(matrix)