Sort list list in Python according to 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 the relevant items in each sublist so that the average sublist is in descending order, which would result in:

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

The second list is now down: [5, 4, 3]. Essentially, I want to reorder the vertical columns in this two-dimensional representation. This seems like an easy task, but it's hard for me to find a solution.

So far I have 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])))

who gave None.

+4
source share
1 answer

, . , , .

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

: print(l.sort(... None, sort , . l.sort(...), print(l). , sorted(l, ...) , . , sorted(l, ...), print(l) , , . l = sorted(l, ...), print(l). ( sort )

+6

Source: https://habr.com/ru/post/1658444/


All Articles