How can I make an itemgetter to enter input from a list variable?

How can I use itemgetter with a list variable instead of integers? For instance:

from operator import itemgetter
z = ['foo', 'bar','qux','zoo']
id = [1,3]

I have no problem with this:

In [5]: itemgetter(1,3)(z)
Out[5]: ('bar', 'zoo')

But this gave an 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 get itemgetter to correctly enter input from a list, i.e. using id?

+4
source share
4 answers

When you do:

print itemgetter(id)(z)

you pass listin itemgetterwhile it expects indexes (integers).

What can you do? You can unzip listwith *:

print itemgetter(*id)(z)

to render it better, both of the following calls are equivalent:

print itemgetter(1, 2, 3)(z)
print itemgetter(*[1, 2, 3])(z)
+8
source

:

>>> indices = [1,3]
>>> itemgetter(*indices)(z)
('bar', 'zoo')

id , .

+4

: itemgetter , , . , , A श wini च haudhary answer, apply ,

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

. apply . . apply .

+1

Source: https://habr.com/ru/post/1535304/


All Articles