有一个类似元组的列表
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 them到 itemgetter
,像这样
>>> 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/