Skip to main content

Posts

Showing posts with the label sort()

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 = ite...