简体   繁体   English

如何让itemgetter从列表变量中获取输入?

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

How can I use itemgetter with list variable instead of integers? 如何将itemgetter与list变量一起使用而不是整数? 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, ie using id ? 如何让itemgetter正确地从列表变量中获取输入,即使用id

When you do: 当你这样做时:

print itemgetter(id)(z)

you are passing a list to itemgetter , while it expects indices (integers). 您将list传递给itemgetter ,而它期望索引(整数)。

What can you do? 你能做什么? You can unpack the list using * : 您可以使用*解压缩list

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. 并且不要使用id作为变量名,它是一个内置函数。

You can take a look at https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists 你可以看看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. itemgetter(*id)(z)将得到你想要的,正如Awini Haudhary已经指出的那样。 Unpacking a dict can be useful too in some cases. 在某些情况下,解包dict也很有用。

The actual problem is, itemgetter expects the list of items to be passed, as individual arguments, but you are passing a single list. 实际问题是, itemgetter期望将项目列表作为单个参数传递,但是您传递的是单个列表。 So, you can unpack like in Aशwini चhaudhary's answer , or you can apply the ids, like this 所以,你可以在Aशwiniचhaudhary的回答中解压缩,或者你可以apply id,像这样

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

Note: apply is actually deprecated. 注意: apply实际上已弃用。 Always prefer unpacking. 总是喜欢打开包装。 I mentioned apply just for the sake of completeness. 我提到的仅仅是为了完整性而apply

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM