I
I
Ivan Melnikov2020-05-27 12:15:33
Python
Ivan Melnikov, 2020-05-27 12:15:33

How to sort a two dimensional list by two columns in python 3?

How to sort by one column is clear:

student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
    ]
student_tuples.sort(key=lambda student: student[2])

How to sort by two columns?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad Grigoriev, 2020-05-27
@immelnikoff

right in the forehead without thinking much

student_tuples = [
...         ('john', 'A', 15),
...         ('jane', 'B', 12),
...         ('dave', 'B', 10),
...         ('dave1', 'B', 11),
...         ('dave2', 'B', 1),
...     ]
... student_tuples.sort(key=lambda student: (student[1], student[2]))
student_tuples
[('john', 'A', 15), ('dave2', 'B', 1), ('dave', 'B', 10), ('dave1', 'B', 11), ('jane', 'B', 12)]

S
Sergey Gornostaev, 2020-05-27
@sergey-gornostaev

The method sortin Python uses stablesort , so you can sort twice - first on one field, then on the other.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question