Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the standard way of doing this sort in Python?

Tags:

python

sorting

Imagine I have a list of tuples in this format:

(1, 2, 3)
(1, 0, 2)
(3, 9 , 11)
(0, 2, 8)
(2, 3, 4)
(2, 4, 5)
(2, 7, 8)
....

How could I sort the list by the first element of the tuples, and then by the second? I'd like to get to this list:

(0, 2, 8)
(1, 0, 2)
(1, 2, 3)
(2, 3, 4)
(2, 4, 5)
(2, 7, 8)
(3, 9 , 11)

I was thinking to do a sort for the first element, and then go through the list, and build a hash with subarrays. I will probably overcomplicate things :), and this is why I asked for other ways of doing this sort.

like image 283
Geo Avatar asked Jun 24 '11 07:06

Geo


1 Answers

Why not simply let python sort the list for you ?

my_list = [
(1, 2, 3),
(1, 0, 2),
(3, 9 , 11),
(0, 2, 8),
(2, 3, 4),
(2, 4, 5),
(2, 7, 8),
]

print sorted(my_list)
>>>[(0, 2, 8), (1, 0, 2), (1, 2, 3), (2, 3, 4), (2, 4, 5), (2, 7, 8), (3, 9, 11)]
like image 186
Cédric Julien Avatar answered Sep 30 '22 13:09

Cédric Julien