I just started learning Python came across this very simple code could not get it right:
import operator;
b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=itemgetter(1))
I got the error:
NameError: name 'itemgetter' is not defined.
Any idea?
itemgetter(*items) Return a callable object that fetches item from its operand using the operand's __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2) , the call f(r) returns r[2] .
itemgetter() can be used to sort the list based on the value of the given key. Note that an error is raised if a dictionary without the specified key is included. You can do the same with a lambda expression. If the dictionary does not have the specified key, you can replace it with any value with the get() method.
In two words operator. itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it. So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.
you must import the module like,
import operator
b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=operator.itemgetter(1))
to write itemgetter
instead of operator.itemgetter
can do
from operator import itemgetter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With