Check if items in list a are found in list b and return list c with matching indexes of list b in Python

391 views Asked by At

I have list a = ["string2" , "string4"] and list b = ["string1" , "string2" , "string3" , "string4" , "string5"] and I want to check if "string2" and "string4" from list a match those in list b and if it does, append list c with it's corresponding index in list b so list c should be [1,3]

My code so far:

for x in a:
    for y in b:
        if x == y:
            print (x)

So I managed to print them out but don't know how to get the index.

Now this is the simpler version of my problem and I could just solve it like this but just for fun I will tell you the whole thing.

I have a list of tuples generated with nltk.word_tokenize in the following format [('string1', 'DT'), ('string2', 'NNP'), ('string3', 'NNP'), ('string4', 'NNP'), ('string5', 'VBZ'), ("string6", 'RB')] and I want to check witch of the words(string1, string2, string3 etc) are found in another list of words (the stopwords list ex: stopwords = ["string312" , "string552" , string631"]) and if found I would like to know their index in my list of tuples by creating another list that will store those indexes or remain empty if none found.

5

There are 5 answers

1
Cory Kramer On BEST ANSWER

You can use index from your second list, while iterating over elements of the first list in a list comprehension.

>>> a = ["string2" , "string4"]
>>> b = ["string1" , "string2" , "string3" , "string4" , "string5"]
>>> c = [b.index(i) for i in a]
>>> c
[1, 3]

If there is a possibility that an element may be in a but not in b then you can modify this slightly

>>> [b.index(i) for i in a if i in b]
[1, 3]
0
Iron Fist On

A continuation to your posted code:

c = []
for x in a:
   for y in b:
       if x == y:
           print(x)
           c.append(b.index(x))
0
Shashank On

You can make a dictionary of element->index by using enumerate on b. This has linear time complexity, but after you complete this step, all of your index lookups will be in constant time O(1), and you'll also have an easy way to see if the value from a could not be found in b, because dict.get will return None. You will also be able to do an O(1) filter operation on a by checking the existence of its elements in the dictionary first, which also makes your second loop have linear time complexity.

>>> a = [50, 150, 250]
>>> b = list(range(200))
>>> bindex = {x: i for i, x in enumerate(b)}
>>> [bindex.get(x) for x in a]
[50, 150, None]
>>> [bindex[x] for x in a if x in bindex]
[50, 150]
0
Rahul Gupta On

Use enumerate combined with list comprehension to get the indexes directly in a list.

>>> [i for i,j in enumerate(b) if j in a]
[1,3]
0
koushik-ksv On

If you are comfortable with sets, you can use the intersection property of sets.

set1 = set(a)
set2 = set(b)
set3 = a & b    #intersection

You can convert back 'set3' to a list and use a list comprehension.

c = list(set3)
[c.index(i) for i in c]