samedi 27 juin 2015

Extract list from given list and given indices

I have a list containinig, more or less, random values. The list always has a fixed length. I have another list containing integer values. These values are always smaller than the length of the first list.

I want to calculate a list containing all values from the first list whose indices are described by the values in the second list. I came up with the following:

>>> values = ['000', '111', '222', '333', '444', '555', '666', '777']
>>> indices = [2, 4, 7]
>>> [v for i, v in enumerate(values) if i in indices]
['222', '444', '777']

As my lists are rather small (24 elements) this is OK for me. Anyway, I wonder if there is some more elegant solution which does not calculate a temporary list (with enumerate()).

Aucun commentaire:

Enregistrer un commentaire