'get indices of strings in a list that are present in another list
l = ['foo','bar','baz']
l2 = ['xbary', 'uobazay', 'zzzfooaa']
How can I get the position of the strings in l that appear in l2?
p = [1,2,0] #because bar is in index 1 of l, baz in index 2 and foo in index 0
Solution 1:[1]
You could use a double for-loop where the inner loop enumerate over l to get the indices:
out = [i for item2 in l2 for i, item1 in enumerate(l) if item1 in item2]
Output:
[1, 2, 0]
Solution 2:[2]
You can also try:
res = [i for elem in l2 for i in range(len(l)) if l[i] in elem]
print(res)
Output:
[1, 2, 0]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Richard K Yu |
