2013-05-10

Python 3: Sort List, Matrix, Object

Perm URL with updates: http://xahlee.info/python/python3_sort.html

This page shows you how to sort in Python

sort Method

You can use the “sort” method. For example:

# -*- coding: utf-8 -*-
# python 3

li = [1,9,2,3]

li.sort() # the variable is modified

print(li) # [1, 2, 3, 9]

sort Function

You can use the “sorted” function. This does not modify the variable. For example:

# -*- coding: utf-8 -*-
# python 3

li = [1,9,2,3]

li2 = sorted(li)

print(li)                       # [1, 9, 2, 3]
print(li2)                      # [1, 2, 3, 9]

sort by Column/Key

You can sort by specifying a optional parameter “key”. This is most useful for sorting a matrix.

# -*- coding: utf-8 -*-
# python 3

# sort a matrix

li = [[2,6],[1,3],[5,4]]

li.sort(key=lambda x:x[1])

print(li);                      # prints [[1, 3], [5, 4], [2, 6]]

Sort and Reverse

Another optional parameter is “reverse”. You can use it like this

# -*- coding: utf-8 -*-
# python 3

# sort a matrix, by 2nd column, reverse order

li = [[2,6],[1,3],[5,4]]

li.sort(key=lambda x:x[1], reverse=True)

print(li);                      # prints [[2, 6], [5, 4], [1, 3]]

Sort Arbitrary Object

Here's a more complex example. Suppose you have a list of strings.

'my283.jpg'
'my23i.jpg'
'web7-s.jpg'
'fris88large.jpg'
…

You want to sort them by the number embedded in them.

You need to define a ordering function, and pass it to sort. The function should takes two strings, and compare the integer inside the string. Here's the solution:

# -*- coding: utf-8 -*-
# python 3

# sort by custom order

import re

li = [
"my283.jpg",
"my23i.jpg",
"web7-s.jpg",
"fris88large.jpg",
]

# compare number inside string
def myKey (myString):
    return float(re.findall(r"\d+", myString)[0]) # return number part in string

li.sort(key = myKey)

print(li) # returns ["web7-s.jpg", "my23i.jpg", "fris88large.jpg", "my283.jpg"]

Here, we defined a function “myKey” to tell sort about the key to use.