Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Python sorting (See related posts)

list.sort() work in place (doesn't return anything)
If you want a version that return result, use sorted() function.
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()    # become [1, 2, 3, 4, 5]
>>> a.sort(cmp) # same as above

>>> a = "This is a test string from Andrew".split()
>>> a.sort(key=str.lower) # using key is simpler
# ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

>>> import operator 
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# itemgetter allows easy Schwartzian transform

3 equivalent ways
- key=operator.itemgetter(1)
- key=lambda x: x[1]
- cmp=lambda a,b: cmp(a[1], b[1])

Learn more at Sorting Howto.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts