python - How does the key argument to sorted work? -


code 1:

>>> sorted("this test string andrew".split(), key=str.lower)     ['a', 'andrew', 'from', 'is', 'string', 'test', 'this'] 

code 2:

>>> student_tuples = [ ...     ('john', 'a', 15), ...     ('jane', 'b', 12), ...     ('dave', 'b', 10), ... ] >>> operator import itemgetter, attrgetter >>> >>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'b', 10), ('jane', 'b', 12), ('john', 'a', 15)] 

why in code 1, () omitted in key=str.lower, , reports error if parentheses included, in code 2 in key=itemgetter(2), parentheses kept?

the key argument sorted expects function, sorted applies each item of thing sorted. results of key(item) compared each other, instead of each original item, during sorting process.

you can imagine working bit this:

def sorted(thing_to_sort, key):     #     # ... lots of complicated stuff ...     #             if key(x) < key(y):                 #             else:                 # else     #     # ... lots more complicated stuff ...     #     return result 

as can see, parentheses () added function key inside sorted, applying x , y, items of thing_to_sort.

in first example, str.lower function gets applied each x , y.

itemgetter bit different. it's function returns function, , in example, it's that other function gets applied x , y.

you can see how itemgetter works in console:

>>> operator import itemgetter >>> item = ('john', 'a', 15) >>> func = itemgetter(2) >>> func(item) 15 

it can little hard head around "higher order" functions (ones accept or return other functions) @ first, they're useful lots of different tasks, it's worth experimenting them until feel comfortable.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -