简体   繁体   中英

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

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.

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)]

Python automagically 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)]

Tuples are already sorted that way.

Try this:

#!/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

If you don't mind sorting by all three elements, this is really trivial:

>>> 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM