Reputation: 21961
I have the following 2 lists in python:
ll = [500,500,500,501,500,502,500]
mm = [499,501,502]
I want to find out the position of last occurence of any item in mm, in the list ll. I can do this for a single element like this:
len(ll) - 1 - ll[::-1].index(502)
>> 5
Here ll[::-1].index(502) provides position of last occurence of 502 and len(ll) - 1 gives the total length.
How do I extend this to work for the entire list mm? I know I can write a function, but is there a more pythonic way
Upvotes: 0
Views: 424
Reputation: 142106
If you want all the last indices of each item in ll
present in mm
, then:
ll = [500,500,500,501,500,502,500]
mm = [499,501,502]
d = {v:k for k,v in enumerate(ll) if v in mm}
# {501: 3, 502: 5}
It's probably worth creating a set
from mm
first to make it an O(1) lookup, instead of O(N), but for three items, it's really not worth it.
Following @Apero's concerns about retaining missing indices as None
and also using a hash lookup to make it an O(1)
lookup...
# Build a key->None dict for all `mm`
d = dict.fromkeys(mm)
# Update `None` values with last index using a gen-exp instead of dict-comp
d.update((v,k) for k,v in enumerate(ll) if v in d)
# {499: None, 501: 3, 502: 5}
Upvotes: 4
Reputation: 8437
results = {}
reversed = ll[::-1]
for item in mm:
try:
index = ((len(ll) - 1) - reversed.index(item))
except ValueError:
index = None
finally:
results[item] = index
print results
Output:
{499: None, 501: 3, 502: 5}
Upvotes: 1
Reputation: 22872
You can do this with a list comprehension and the max
function. In particular, for each element in ll
, iterate through mm
to create a list of indices where ll[i] = mm[i]
, and take the max
of this list.
>>> indices = [ max([-1] + [i for i, m in enumerate(mm) if m == n]) for n in ll ]
>>> indices
[-1, -1, -1, 1, -1, 2, -1]
Note that you need to add [-1]
in case there are no matching indices in mm
.
All this being said, I don't think it's more Python-ic than writing a function and using a list comprehension (as you alluded to in your question).
Upvotes: 0