Sundrah
Sundrah

Reputation: 865

Python - how to print values of a list given many indexes?

I have for example the index values:

x = [1, 4, 5, 7]

and I have a list of elements:

y = ['this','is','a','very','short','sentence','for','testing']

I want to return the values

['is','short','sentence','testing']

When I attempt to print say:

y[1]

it will gladly return ['is']. However, when I do print(y[x])) it will simply return nothing. How can I print all those indexes? Bonus: Then join them together.

Upvotes: 0

Views: 5336

Answers (4)

jh liu
jh liu

Reputation: 72

If you have numpy package, you can do like this

>>> import numpy as np
>>> y = np.array(['this','is','a','very','short','sentence','for','testing'])
>>> x = np.array([1,4,5,7])
>>> print y[x]
['is' 'short' 'sentence' 'testing']

Upvotes: 1

four-eyes
four-eyes

Reputation: 12394

You will need a for loop to iterate through your list of indexes and then axes your list with the indexes.

for i in x: #x is your list, i will take the 'value' of the numbers in your list and will be your indexed
    print y[i]

    > is
      short
      sentence
      testing

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52071

Try this list comp [y[i] for i in x]

>>> y = ['this','is','a','very','short','sentence','for','testing']
>>> x = [1, 4, 5, 7]
>>> [y[i] for i in x]                    # List comprehension to get strings
['is', 'short', 'sentence', 'testing']
>>> ' '.join([y[i] for i in x])          # Join on that for your bonus
'is short sentence testing'

Other ways

>>> list(map(lambda i:y[i], x) )         # Using map
['is', 'short', 'sentence', 'testing']

Upvotes: 2

agamagarwal
agamagarwal

Reputation: 988

This should do the job:

' '.join([y[i] for i in x])

Upvotes: 1

Related Questions