+ 1
How does this code works ?
I ran this code many times but I couldn't get it. my_list = ['car','plane','train','bike','rocket'] new_list = sorted(my_list, key = lambda x: x[-2]) print(new_list) Answer is ['car','rocket','train','bike','plane']
2 RĂ©ponses
+ 5
Normally, when you sort strings, they are compared lexically, letter by letter, about what you'd do in a dictionary.
Now the added key function means:
'Instead of what you usually compare, compare what this function returns.'
The lambda function returns the letter at index -2 (second before last letter), so only that is gonna get compared.
Now look at the second last letter of each word in the final list:
a, e, i, k, n
Perfectly sorted.
+ 2
key parameter takes a function, which every elements would pass to. Then it sorts the return values.
In this case, the lambda returns the second last character of a string since you pass a list of strings.
car -> a
rocket -> e
train -> i
bike -> k
plane -> n
It's Alphabetical.