python - 如果给定 python 中的一些元组索引,如何获取子元组列表?

标签 python list tuples

有一个类似元组的列表

l = [(1, 2, 'a', 'b'), (3, 4, 'c', 'd'), (5, 6, 'e', 'f')]

我可以用

[(i[0], i[2], i[3]) for i in l]

得到结果

[(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')]

但是如果给定一个变量列表,比如[0, 2, 3],如何得到相似的结果呢?

最佳答案

使用operator.itemgetter , 像这样

>>> from operator import itemgetter
>>> getter = itemgetter(0, 2, 3)
>>> [getter(item) for item in l]
[(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')]

如果你有一个索引列表,那么你可以 unpack themitemgetter,像这样

>>> getter = itemgetter(*[0, 2, 3])
>>> [getter(item) for item in l]
[(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')]

关于python - 如果给定 python 中的一些元组索引,如何获取子元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28937293/

相关文章:

python - 只打开和读取最新的 json 文件一次

python - 性能比较 静态类型 Python 3.6+ 与 Cython

c - 链表初学者

sql - 如果在列中交换相同的值,则元组是重复的,如何删除 Oracle SQL 中的重复项?

c++ - 程序可以在 Mac 上编译,但不能在 Linux 上编译。获取错误 : converting to from initializer list

python - 如何制作自己的命令

python - URL 查询参数作为 Pyramid 中的字典

C# 字典与列表用法

Python 添加到列表

python - 删除集合中已经存在于另一个元组中的元组对