Home > Enterprise >  How to access specific values inside a list that are stored in a idx variable? (python)
How to access specific values inside a list that are stored in a idx variable? (python)

Time:12-28

I obtain by a "certain process" an index idx array. So now I would like to access those elements in the a list. In R this is pretty straightforward, but I can't find an easy solution in python without using for-loops.

this below is the code:

a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
idx = [2,4,7,8]

print(a[idx])  #  -->  R approach
#output should be --> "word3" "word5" "word8" "word9"

How can I solve this simple task? Thanks

CodePudding user response:

You can use operator.itemgetter:

>>> from operator import itemgetter
>>> a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
>>> idx = [2,4,7,8]
>>> itemgetter(*idx)(a)
('word3', 'word5', 'word8', 'word9')

CodePudding user response:

The short and simple way is to use a list or generator comprehension and use a starred expression to unpack all of its values:

a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
idx = [2,4,7,8]

print(*(a[i] for i in idx))

# Output:
# word3 word5 word8 word9

If you wanted to replicate R behaviour, you can create your own custom class and alter its __getitem__ method a bit to check whether the argument was a list or a tuple (or really any object that has __iter__ method) and then return what R returns (basically using the same method as above):

class List(list):
    def __getitem__(self, index):
        if hasattr(index, '__iter__'):
            return [self[i] for i in index]
        return super().__getitem__(index)


a = ["word1", "word2", "word3", "word4", "word5", "word6", "word7", "word8", "word9"]
b = List(a)
idx = [2, 4, 7, 8]

print(b[idx])  # add star before to print only the values without the list and stuff
  • Related