Suppose 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 can I sort the list by the first element of tuples and then by the second? I would like to get on 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 of pretending to look for the first element, and then go through the list and build a hash with subarrays. I probably confuse things :) and that is why I asked for other ways to do this.
Why not just 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)]
Python automatically does the right thing:
>>> a = [(1, 2, 3), (1, 0, 2), (3, 9, 11), (0, 2, 8), (2, 3, 4), (2, 4, 5), (2, 7, 8)] >>> a.sort() >>> a [(0, 2, 8), (1, 0, 2), (1, 2, 3), (2, 3, 4), (2, 4, 5), (2, 7, 8), (3, 9, 11)]
.
:
#!/usr/bin/python2 l = [ (1, 2, 3), (1, 0, 2), (3, 9 , 11), (0, 2, 8), (2, 3, 4), (2, 4, 5), (2, 7, 8), ] l.sort() print l
, :
>>> l = [(1, 2, 3), (1, 0, 2), (3, 9, 11), (0, 2, 8), (2, 3, 4), (2, 4, 5), (2, 7, 8)] >>> l.sort() >>> l [(0, 2, 8), (1, 0, 2), (1, 2, 3), (2, 3, 4), (2, 4, 5), (2, 7, 8), (3, 9, 11)]
>>> x = [ ... (1, 2, 3), ... (1, 0, 2), ... (3, 9 , 11), ... (0, 2, 8), ... (2, 3, 4), ... (2, 4, 5), ... (2, 7, 8), ... ] >>> x.sort() >>> x [(0, 2, 8), (1, 0, 2), (1, 2, 3), (2, 3, 4), (2, 4, 5), (2, 7, 8), (3, 9, 11)]