如果在python中给出一些元组索引,如何获取子元组列表?

wan*_*020 3 python tuples list

有一个元组列表

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

我可以用

[(i[0], i[2], i[3]) for i in l]
Run Code Online (Sandbox Code Playgroud)

得到结果

[(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')]
Run Code Online (Sandbox Code Playgroud)

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

the*_*eye 8

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')]
Run Code Online (Sandbox Code Playgroud)

如果你有一个索引列表,那么你可以将它们解压缩itemgetter,就像这样

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


Mar*_*ers 5

您可以使用生成器表达式并tuple()提取特定索引:

[tuple(t[i] for i in indices) for t in l]
Run Code Online (Sandbox Code Playgroud)

或者你可以使用一个operator.itemgetter()对象来创建一个相同的callable:

from operator import itemgetter

getindices = itemgetter(*indices)
[getindices(t) for t in l]
Run Code Online (Sandbox Code Playgroud)

indices您的索引列表在哪里.这是有效的,因为在检索多个索引时operator.itemgetter()恰好返回一个tuple对象.

演示:

>>> l = [(1, 2, 'a', 'b'), (3, 4, 'c','d'), (5, 6, 'e','f')]
>>> indices = [0, 1, 2]
>>> [tuple(t[i] for i in indices) for t in l]
[(1, 2, 'a'), (3, 4, 'c'), (5, 6, 'e')]
>>> getindices = itemgetter(*indices)
>>> from operator import itemgetter
>>> [getindices(t) for t in l]
[(1, 2, 'a'), (3, 4, 'c'), (5, 6, 'e')]
Run Code Online (Sandbox Code Playgroud)