1

So I have a 2D array of data taken from an excel spreadsheet which I'm currently sorting based on a column with data on criticality.

#rows contains my data that I'm sorting, it's a 2D array
searchdict = dict(Critical=1, High=2, Medium=3, Low=4)
rows.sort(key=lambda row: searchdict.get(row[11], 5))

I'd like to sort based on another column if it's a tie for that column, anyone know how to approach this? Thanks in advance for any help.

FYI: the other column contains numerical data

avorum
  • 2,243
  • 10
  • 39
  • 49
  • http://stackoverflow.com/questions/1516249/python-list-sorting-with-multiple-attributes-and-mixed-order – georg May 31 '13 at 22:20

3 Answers3

8

Use a tuple in your key. This is method is generally considered more "pythonic" than doing two sorts in a row.

key=lambda row: (searchdict.get(row[11], 5), row[other_column]))
JAB
  • 20,783
  • 6
  • 71
  • 80
  • The OP said that the other column is numerical so there is no need for an other call to `searchdict.get`. (BTW: thg's answer was incorrect also because if you want to do 2 sorts you must first sort by the *secondary key*, and the by the primary key.) – Bakuriu May 31 '13 at 20:27
  • 1
    Oops, you're right. And thg's answer was also incorrect because `sort()` normally returns `None` instead of the sorted list (`sorted()` is normally used for that). – JAB May 31 '13 at 20:33
1

The best option would be to use key with python's tuple ordering.

#rows contains my data that I'm sorting, it's a 2D array
searchdict = dict(Critical=1, High=2, Medium=3, Low=4)
rows.sort(key=lambda row: (searchdict.get(row[11], 5), searchdict.get(row[<secondary column index here>], 5)))

This plays off of the fact that the leftmost element in a tuple is considered to be more significant during comparisons, demonstrated here:

>>> (6, 5) > (5, 6)
True
>>> (6, 5) > (6, 4)
True
>>> (6, 5) > (6, 6)
False
>>> (2, 1, 1) > (1, 1000, 1000)
True 
gepoch
  • 711
  • 6
  • 17
0

Use a tuple as return from your sort key function:

rows.sort(key=lambda row: (searchdict.get(row[11], 5), row[17]))

Python sorts for item with index 0 first than for item with index 1.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161