HappyPy
HappyPy

Reputation: 10697

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

Upvotes: 0

Views: 452

Answers (2)

Richard K Yu
Richard K Yu

Reputation: 2202

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]

Upvotes: 1

user7864386
user7864386

Reputation:

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]

Upvotes: 1

Related Questions