0

I have this code wrote in Python that is for inputting a matrix:

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

For example,a resulting matrix would be

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

I would like to know if there's any way to sort the lines and columns of it? For example, sorting the first line would result in [2, 4, 9] and sorting the first column would result [7, 9].

tshepang
  • 12,111
  • 21
  • 91
  • 136
Jon_Computer
  • 689
  • 2
  • 6
  • 9
  • 1
    Unless you're looking for a nice programming exercise these operations are much easier using numpy. See http://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column for more details. – user1603472 Apr 18 '14 at 14:14

2 Answers2

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()

Now if you want to sort columns of your matrix do

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

With rows it will be even simpler, I'd go for

for row in matrix:
    row.sort()
Dunno
  • 3,632
  • 3
  • 28
  • 43
0
matrix = []
while True:
    line = input()
    if not line: break
    values = line.split()
    row = [int(value) for value in values]
    matrix.append(row.sort())

And then just print sort it by columns with:

sorted(matrix)
Krzysztof Wende
  • 3,208
  • 25
  • 38