I was amazed to how many ways there were to sort lists in Python. Better yet, you DON'T need to create a new function to sort things like you do in PHP.
Basic Sorting
Create a copy of the list
1.
sorted([
5
,
2
,
3
,
1
,
4
])
2.
3.
[
1
,
2
,
3
,
4
,
5
]
Sort and modify the list
This method only works for lists.
1.
a
=
[
5
,
2
,
3
,
1
,
4
]
2.
a.sort()
3.
a
4.
5.
[
1
,
2
,
3
,
4
,
5
]
Sort by Key
Pyhon 2.4 brings the "key" argument to sorted().
For example, we use the tuple:
1.
student_tuples
=
[
2.
(
'john'
,
'A'
,
15
),
3.
(
'jane'
,
'B'
,
12
),
4.
(
'dave'
,
'B'
,
10
),
5.
]
6.
sorted(student_tuples, key
=
lambda
student: student[
2
])
# sort by age
7.
8.
[(
'dave'
,
'B'
,
10
), (
'jane'
,
'B'
,
12
), (
'john'
,
'A'
,
15
)]
Or a class:
01.
class
Student:
02.
def
__init__(
self
, name, grade, age):
03.
self
.name
=
name
04.
self
.grade
=
grade
05.
self
.age
=
age
06.
07.
student_objects
=
[
08.
Student(
'john'
,
'A'
,
15
),
09.
Student(
'jane'
,
'B'
,
12
),
10.
Student(
'dave'
,
'B'
,
10
),
11.
]
12.
sorted(student_objects, key
=
lambda
student: student.age)
# sort by age
13.
14.
[(
'dave'
,
'B'
,
10
), (
'jane'
,
'B'
,
12
), (
'john'
,
'A'
,
15
)]
Sort by key has some helper functions called itemgetter() and attrgetter() which do what the above examples do. It also allows for multiple levels of sorting.
1.
from
operator
import
itemgetter, attrgetter
2.
3.
sorted(student_tuples, key
=
itemgetter(
1
,
2
))
4.
[(
'john'
,
'A'
,
15
), (
'dave'
,
'B'
,
10
), (
'jane'
,
'B'
,
12
)]
5.
6.
sorted(student_objects, key
=
attrgetter(
'grade'
,
'age'
))
7.
[(
'john'
,
'A'
,
15
), (
'dave'
,
'B'
,
10
), (
'jane'
,
'B'
,
12
)]
Reverse order
Easy enough, there's a "reverse" argument in sorted() to do that.
1.
sorted(a, reverse
=
True
)
Source
This post was an extract of the things I found helpful from the Python wiki docs. See the link below for more information.