I am trying to sort a two-dimensional array by the second element by numbers from highest to lowest. But in return I get some kind of garbage. It works, it doesn’t. Some kind of accident.
Apparently, I’m doing something wrong. Please point out my mistake and, if it does not bother you, send your version.
Answer 1, authority 100%
By default, the elements of the array are sorted directly, in your case – arrays. If you need to sort by a specific parameter of an element, then you need to pass a function that returns the required parameter to the based
key parameter, in your case – the second element of the array. It can be defined as a regular function via
def or as a lambda expression, as in my example.
arr = [['asd', 4], ['fgh', 5], ['jkl', 3]] print (arr) arr.sort (key = lambda x: x ) print (arr)
[['asd', 4], ['fgh', 5], ['jkl', 3] ] [['jkl', 3], ['asd', 4], ['fgh', 5]]