ste ste - 1 year ago 84
Python Question

Sort list of list in Python according to a specific column

I have a list of lists that looks like this:

l = [[1, 2, 3],
[3, 5, 4],
[9, 8, 7]]

I want to sort corresponding elements in each sublist so that the middle sublist would be in descending order, which would result in:

l = [[2, 3, 1],
[5, 4, 3],
[8, 7, 9]]

The second list is now descending:
[5, 4, 3]
. Essentially, I want reorder the vertical columns in that 2D representation. It seems like an easy task, but I had difficulties finding a solution.

So far I tried:

from operator import itemgetter
sorted(l, key=itemgetter(1))

which didn't change anything and I tried

print(l.sort(key = lambda row: (row[1])))

which gave None.

Answer Source

The attempts you made will sort by values in the second column, but you want to sort by values in the second row. So transpose the list, sort by column, then transpose back.

>>> l = [[1, 2, 3], [3, 5, 4], [9, 8, 7]]
>>> transposed_l = zip(*l)
>>> transposed_l.sort(key=lambda x: x[1], reverse=True)
>>> l = zip(*transposed_l)
>>> l
[(2, 3, 1), (5, 4, 3), (8, 7, 9)]

Bonus tip: your print(l.sort(... approach printed None because sort doesn't return anything, it sorts in-place. So you should instead do l.sort(...) and then print(l). Conversely, your sorted(l, ...) attempt didn't appear to do anything because it doesn't sort in-place, and instead returns a brand new list. I'm guessing you did sorted(l, ...) and then print(l) and were surprised to see nothing changed. You might instead do l = sorted(l, ...) and then print(l). (although just using sort would be more idiomatic)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download