Python sorting - A list of objects

Tuesday, March 23, 2010

In [1]: import operator

In [2]: L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]

In [3]: sorted(L, key=operator.itemgetter(0))
Out[3]: [('a', 4), ('b', 3), ('c', 2), ('d', 1)]

In [4]: sorted(L, key=operator.itemgetter(1))
Out[4]: [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

This entry was tagged Python and sorting

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top