2

I am trying to make a function which takes a table (list of lists) to sort. The function should sort the table so that a specified row is in increasing order. All other rows are sorted according to this specified row.

For example: I have a table:

[['A','B','C'],
[3,4,2]]

and I want to sort this according to the second row. I'm expecting my function to return the sorted table:

[['C','A','B'],
[2,3,4]]

This is my attempt:

def sort2DListByList(table, sortIndex):
    # Take a 2D list and an index of the table row to sort by and return the
    #sorted table.
    # Sort list in increasing order.
    sortList = table[sortIndex]
    # newTable will be populated with ordered values.
    # Create newTable full of zeros.
    newTable = [[0]*len(table[0])]*len(table)
    maximum = max(sortList)
    for i in range(len(sortList)):
        minimum = min(sortList)
        minIndex = sortList.index(minimum)
        for j in range(len(table)):
            newTable[j][i] = table[j][minIndex]
        # Fill the minimum with a maximum so it is not found again.
        sortList[minIndex] = maximum+1
    return newTable

table = [['A','B','C'],[3,4,2]]
sortedTable = sort2DListByList(table, 1)

print(sortedTable)

When I run this code I get an output

[[2, 3, 4], [2, 3, 4]]

I cannot understand why the letters in the first row did not get copied over to the new table. This must be a simple error but I just can't see it.

Hugh
  • 413
  • 1
  • 5
  • 12

0 Answers0