Meep
Meep

Reputation: 387

Set of indices corresponding to a set of elements in a list python3

I have referred to this post for finding the index(ices) corresponding to a single named element in a list, but have not been able to find an answer to my query among the answers there/documentation.

Specifically: is there a more efficient way than just iterating the method in the link above, for finding the indices corresponding to a set of elements?

Say I have the list

mybiglist=['abc','def','ghi','jkl','mno']

and I want the indices corresponding to 'abc','jkl'

I could do:

mytargetlist=['abc','jkl']
for string in mytargetlist:
    print(mybiglist.index('%s' %string))

But it feels like there should be a more efficient way than a loop?

In case the context makes a difference, I am trying to find the indices corresponding to certain vertices in a graph, so that I can use induce_subgraph to create a subgraph containing these vertices. Unfortunately I only know the name labels that I want, and which are attributed to the vertices, and the arguments of induce_subraph are: induce_subgraph(graph, vertex set)

Upvotes: 0

Views: 64

Answers (4)

jsa
jsa

Reputation: 397

This will split your target list in chunks and launch separate threads. More info here:

import concurrent.futures

mybiglist=['abc','def','ghi','jkl','mno']
mytargetlist=['abc','jkl']

def get_index(x):
    return mybiglist.index(x)

with concurrent.futures.ProcessPoolExecutor() as executor:
    results = executor.map(get_index, mytargetlist)

print(list(results))

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150805

mybiglist.index(string) has complexity O(n), so basically you do a double for loop on mybiglist and mytargetlist. You could improve by enumerate:

indices = {v:i for i,v in enumerate(mybiglist)}

and you can access the indices later, i.e. indices['abc'].

Upvotes: 0

Adam.Er8
Adam.Er8

Reputation: 13413

I think your way is kind of simple, maybe could be simplified more with list comprehensions (that's just syntactic sugar...):

mybiglist = ['abc', 'def', 'ghi', 'jkl', 'mno']
mytargetlist = ['abc', 'jkl']
print([mybiglist.index(target) for target in mytargetlist])

if you want an overkill solution you can use numpy with isin and where to get the indices without iterating over it yourself:

import numpy as np

mybiglist = np.array(['abc', 'def', 'ghi', 'jkl', 'mno'], dtype=str)
mytargetlist = ['abc', 'jkl']

print(*np.where(np.isin(mybiglist, mytargetlist)))

but that seems a little ridiculous :P

Upvotes: 0

Kyle Parsons
Kyle Parsons

Reputation: 1525

You can do it once through your big list with a comprehension.

mybiglist=['abc','def','ghi','jkl','mno']
mytargetlist=['abc','jkl']

[i for i, v in enumerate(mybiglist) if v in mytargetlist]

Upvotes: 1

Related Questions