Python sort() patterns

Python has a lot of sorting patterns. Let's make a short a list.

1. Sorting list by it's element. Simple case. Should simply do:

>>> exmpl_list =['a', 'c', 'B', 'd']
>>> exmpl_list.sort()
['a', 'B', 'c', 'd']
However this example does not take locale into account and works only for ASCII characters.

2. Sorting list of sub elements.


exmpl_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]  
# Sorting by 'name'  
newlist = sorted(exmpl_list, key=lambda k: k['name'])
# Better way to use itemgetter():
from operator import itemgetter
newlist = sorted(exmpl_list, key=itemgetter('name'))
Note that it is equivalent to:

exmpl_list.sort(key=lambda k: k['name'])
# OR:
exmpl_list.sort(key=itemgetter('name'))
if you do not need new list in result.

3. Local aware decision


import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

4. Sorting list of tuples/lists by known element position:


data = [[1,2,3], [4,5,6], [7,8,9]] 
data = [(1,2,3), (4,5,6), (7,8,9)]
 
sorted_by_second = sorted(data, key=lambda tup: tup[1])
data.sort(key=lambda tup: tup[1])  # sorts in place

BTW. Python How To: Sorting

Comments

Popular posts from this blog

Django: Resetting Passwords (with internal tools)

Python converting PDF to Image

Django: Beautiful multiple files Upload Plugin using jQuery UI.