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

标签 python operator-keyword

如何将 itemgetter 与列表变量而不是整数一起使用? 例如:

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

我这样做没问题:

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

但是当我这样做时出现错误:

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

如何使 itemgetter 正确地从列表变量中获取输入,即使用 id

最佳答案

当你这样做时:

print itemgetter(id)(z)

您正在将 list 传递给 itemgetter,而它需要索引(整数)。

你能做什么?你可以使用 * 解压 list:

print itemgetter(*id)(z)

为了更好地形象化,以下两个调用是等效的:

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

关于python - 如何让 itemgetter 从列表变量中获取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903770/

相关文章:

c++ - 程序输出(C++ 的基本运算符)。操作顺序?

c++ - 我的程序因运算符过载而不断出现段错误

C++ 运算符重载总是 false

javascript - 将大整数数组从 javascript 传输到 Flask 的优化方法,反之亦然

python - “int”对象不可迭代

python - 如何使用 RSA 加密和解密 AES key 并将其存储在文本文件中

c++ - 嵌套的 if 语句和 "&&"运算符

python - 从 PDF 中搜索文本的脚本

python - 超越关键字依赖的文本分类并推断实际含义

jquery - TaffyDB OR 运算符如何?