Вопрос

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?

Это было полезно?

Решение

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.

You can take a look at https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

itemgetter(*id)(z) will get what you want as already pointed out by Awini Haudhary. Unpacking a dict can be useful too in some cases.

The actual problem is, itemgetter expects the list of items to be passed, as individual arguments, but you are passing a single list. So, you can unpack like in Aशwini चhaudhary's answer, or you can apply the ids, like this

print apply(itemgetter, ids)(z)
# ('bar', 'zoo')

Note: apply is actually deprecated. Always prefer unpacking. I mentioned apply just for the sake of completeness.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top