Reputation: 676
I am comparing two lists in Python.
list1
is a superset of list2
.
For the elements of list1
, I want their index in list2
(if present).
Here are two examples.
list1 = ['a','b','c','d']
list2 = ['a','b']
The solution should produce [0, 1]
.
list1 = ['a','b','c','d']
list2 = ['b','a']
The solution should produce [1, 0]
.
I attempted the following code, but it only works for the first example.
list1 = ['a','b','c','d']
list2 = ['a','b']
pairwise = zip(list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
This works. However, for the second set of sample data I get the wrong output []
instead of the expected output [1, 0]
.
list1 = ['a','b','c','d']
list2 = ['b','a']
pairwise = zip (list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
print(matched_index) # prints []
Please suggest the way forward.
Upvotes: 3
Views: 3835
Reputation: 3704
Assuming there are unique elements in each list and len(list1) >= len(list2)
>>> list1 = ['a','b','c','d']
>>> list2 = ['d','a', 'f']
>>> print([list2.index(x) for x in list1 if x in list2])
Upvotes: 0
Reputation: 164673
Since list2
is a subset of list1
, you can construct a dictionary mapping and then use dict.__getitem__
on values of list2
to extract indices:
list1 = ['a','b','c','d']
list2 = ['a','b']
list3 = ['b','a']
d = {v: k for k, v in enumerate(list1)}
res1 = list(map(d.__getitem__, list2)) # [0, 1]
res2 = list(map(d.__getitem__, list3)) # [1, 0]
Upvotes: 2
Reputation: 78690
I suggest using a dictionary mapping the elements of list2
to their index - assuming list2
has unique elements.
>>> list1 = ['a','b','c','d']
>>> list2 = ['b','a']
>>> idx = {x:i for i,x in enumerate(list2)}
>>> idx
{'a': 1, 'b': 0}
Now you can issue
>>> [idx[x] for x in list1 if x in idx]
[1, 0]
Upvotes: 3