AaronDT
AaronDT

Reputation: 4060

2d array list comprehension with an index lookup

I have a simple 2d array like so:

arr = [[2,1,0],[0,2,1]]

Now I am trying to replace the values inside the 2d array with values from a list by using the values inside the array as the index of the list. For example my list looks like this:

list = ['Cat', 'Dog', 'Fox']

I am trying to get a result like this:

[['Fox','Dog','Cat'],['Cat','Fox','Dog']]

I trying to figure out how to do this efficiently using list comprehensions, however I can't find a way that seems works.

I thought this should work:

[list[x] for x in y for y in arr ]

However, it tells me NameError: name 'y' is not defined

Upvotes: 1

Views: 89

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do:

arr = [[2,1,0],[0,2,1]]

lst = ['Cat', 'Dog', 'Fox']

result = [[lst[i] for i in sublist] for sublist in arr]

print(result)

Output

[['Fox', 'Dog', 'Cat'], ['Cat', 'Fox', 'Dog']]

Upvotes: 5

Related Questions