P
P
Proritsatel2020-08-27 15:43:42
Python
Proritsatel, 2020-08-27 15:43:42

How to sort a list using lambda?

Good day!
There is a list:

lst = ['1:ooo', '1:ii', '1:uuu', '2:dd','=:nnn' , '=:gg', '2:ee','2:sss' , '2:aa']

I need to get a list like this:
["1:ooo", "1:uuu", "2:sss", "=:nnn", "1:ii", "2:aa", "2:dd", "2:ee", "=:gg"]

What I do: I
sort by three parameters: by length, by first character, and by character placeholder alphabetically.
lst.sort(key=lambda x:(len(x), x[0], x[2]))
I get:
['1:ii', '2:aa', '2:dd', '2:ee', '=:gg', '1:ooo', '1:uuu', '2:sss', '=:nnn']


As I understand it, I need to sort by length, in reverse order, but I don’t know how to set it, I can only set it at the end of the tuple:
lst.sort(key=lambda x:(len(x), x[0], x[2]), reverse=True)

But then it doesn't work that way:
['=:nnn', '2:sss', '1:uuu', '1:ooo', '=:gg', '2:ee', '2:dd', '2:aa', '1:ii']


Help solve this problem

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2020-08-27
@Proritsatel

Put a minus in front of len, it will be in reverse order in length

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question