Home python Sort a two-dimensional array by 1 element

Sort a two-dimensional array by 1 element

Author

Date

Category

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 [1])
print (arr)

Output:

[['asd', 4], ['fgh', 5], ['jkl', 3] ]
[['jkl', 3], ['asd', 4], ['fgh', 5]]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions