Reputation: 183
New to python so apologies if this is trivial. I have a list
list = [3,1,0,2]
and a nested lookup
lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]
I need to match every element in "list" with each corresponding element index in "lookup" and return the value of this element from "lookup". The result should be:
result = [
[28,82,158],
[225,302,191],
[265,301,201],
[225,35,134]
]
Upvotes: 3
Views: 126
Reputation: 180391
A regular list comp and indexing:
lst = [3,1,0,2]
print([lookup[i] for i in lst])
[[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]
Or a functional approach using __getitem__
:
lst = [3,1,0,2]
lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]
print(list(map(lookup.__getitem__, lst)))
[[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]
using operator.itemgetter
:
lst = [3,1,0,2]
lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]
from operator import itemgetter
print(list(itemgetter(*lst)(lookup)))
[[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]
Upvotes: 3
Reputation: 19733
you can use map and lambda too:
>>> lst = [3, 1, 0, 2]
>>> lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]
>>> map(lambda x:lookup[x], lst)
[[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]
Upvotes: 1
Reputation: 601441
You can use a list comprehension:
result = [lookup[i] for i in list]
(Note that you shouldn't call a variable list
. It will shadow the builtin of the same name, and will lead to unexpected beahaviour sooner or later.)
Upvotes: 3