How can I use itemgetter with list variable instead of integers? For example:
from operator import itemgetter
z = ['foo', 'bar','qux','zoo']
id = [1,3]
I have no problem doing this:
In [5]: itemgetter(1,3)(z)
Out[5]: ('bar', 'zoo')
But it gave error when I do this:
In [7]: itemgetter(id)(z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-7ba47b19f282> in <module>()
----> 1 itemgetter(id)(z)
TypeError: list indices must be integers, not list
How can I make itemgetter to take input from list variable correctly, i.e. using id
?
To sort by more than one column you can use itemgetter with multiple indices: operator. itemgetter(1,2) , or with lambda: lambda elem: (elem[1], elem[2]) . This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?)
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.
itemgetter() that fetches an “item” using the operand's __getitem__() method. If multiple values are returned, the function returns them in a tuple. This function works with Python dictionaries, strings, lists, and tuples.
When you do:
print itemgetter(id)(z)
you are passing a list
to itemgetter
, while it expects indices (integers).
What can you do? You can unpack the list
using *
:
print itemgetter(*id)(z)
to visualize this better, both following calls are equivalent:
print itemgetter(1, 2, 3)(z)
print itemgetter(*[1, 2, 3])(z)
Use argument unpacking:
>>> indices = [1,3]
>>> itemgetter(*indices)(z)
('bar', 'zoo')
And don't use id
as a variable name, it's a built-in function.
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