简体   繁体   中英

How to get a list of sub tuple if given some indexes of tuple in python?

There is a list of tuple like

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

I can use

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

to get the result

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

But if given a variable list such as [0, 2, 3] , how to get the similar result?

Use operator.itemgetter , like this

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

If you have a list of indices, then you can unpack them to the itemgetter , like this

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

You could use a generator expression and tuple() to pull out specific indices:

[tuple(t[i] for i in indices) for t in l]

or you can use a operator.itemgetter() object to create a callable that does the same:

from operator import itemgetter

getindices = itemgetter(*indices)
[getindices(t) for t in l]

where indices is your list of indexes. This works because operator.itemgetter() just happens to return a tuple object when retrieving multiple indexes.

Demo:

>>> 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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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