Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make itemgetter to take input from list variable?

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?

like image 326
pdubois Avatar asked Apr 07 '14 04:04

pdubois


People also ask

How do you sort a list using Itemgetter in Python?

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(?)

How do I use key Itemgetter in Python?

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.

How does Itemgetter work in Python?

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.


2 Answers

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)
like image 166
Christian Tapia Avatar answered Oct 08 '22 03:10

Christian Tapia


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.

like image 5
Ashwini Chaudhary Avatar answered Oct 08 '22 01:10

Ashwini Chaudhary