HoneyWeGOTissues
HoneyWeGOTissues

Reputation: 71

Filling index list with correct values

I have a list of index values. I want to match the index value to the correct information from an np array. How would I do this?

example:

index = [1, -2, -2, 0]

#where -2 values are omitted, not present in array

array = ['grape''purple''lizard', 'apple''red''monkey']

wanted output:

new array = ['apple''red''monkey',-2, -2,'grape''purple''lizard']

Upvotes: -1

Views: 23

Answers (1)

mozway
mozway

Reputation: 262224

You can use a list comprehension with a test on the bounds of array:

new_array = [array[i] if 0<=i<len(array) else i for i in index]

output: ['appleredmonkey', -2, -2, 'grapepurplelizard']

NB. 'apple''red''monkey' is strictly equivalent to 'appleredmonkey' due to implicit string concatenation in python.

Upvotes: 0

Related Questions