0

I want to select multiple groups of three or more elements from a list, according to some indices.

I thought of using itemgetter, but it does not work for multiple sets, for example

labels=['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15']
indexlist = list(itertools.combinations(range(1, 10), 3))
ixs= [4,5]
a=[indexlist[ix] for ix in ixs]
from operator import itemgetter
print(*itemgetter(*a[0])(labels))

where

a=[(1, 2, 7), (1, 2, 8)]

works well, whereas

labels=['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15']
indexlist = list(itertools.combinations(range(1, 10), 3))
ixs= [4,5]
a=[indexlist[ix] for ix in ixs]
from operator import itemgetter
print(*itemgetter(*a)(labels))

gives the error

list indices must be integers or slices, not list

Is there a way to pass multiple sets of indices to itemgetter, or is there some other convenient alternative?

1 Answers1

0

You are trying to parse several indexes, as stated. To make it easier you can use numpy.

labels = np.array(['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15'])
print([list(labels[index_tuples])] for index_tuples in a)

What this is doing is getting multiple sets of indexes using your tuples and printing them as a list.

Source: Access multiple elements of list knowing their index

Larry the Llama
  • 958
  • 3
  • 13
  • I am not sure how to use that generator, if I inquire ```list(labels[a[0]])``` I get ```IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed``` – Daniele Marinazzo Nov 17 '21 at 10:20