Home > Software design >  iterate and compare two lists in python, if contains string from the other list, pop item
iterate and compare two lists in python, if contains string from the other list, pop item

Time:07-03

I'm trying to comparing two lists (mama and filterkeywords in the code shown), and remove values from the first list depending on the second. I have this code:

occurenceList = []
title = ['SL C ','FS D ','FS H','FS F','FS D','SL C','SL F','FS H','SL H','SL D']
mama = ['slow cat Sas','fast dog PoP','fast hen Luke','fast fish Lee','fast dog joe','slow cat yan','slow fish ben','Fast hen Tim','Slow hen Jen','slow dog moe']
filterkeywords = ['hen','dog','fish','Fish']

print(" ")
for text in mama:
   for words in filterkeywords:
      if words in text:
         animal = (mama.index(text))
         print("index: ", animal, ' | ', mama[animal], " | Word Found: ", words)
         title.pop(animal)
         mama.pop(animal)

print(" ")
for items in title:
   itemindex = title.index(items)
   print(itemindex, " ", items,' ',mama[itemindex])

Which gives this output:

index:  1  |  fast dog PoP  | Word Found:  dog
index:  2  |  fast fish Lee  | Word Found:  fish
index:  4  |  slow fish ben  | Word Found:  fish
index:  5  |  Slow hen Jen  | Word Found:  hen
 
0   SL C    slow cat Sas
1   FS H   fast hen Luke
2   FS D   fast dog joe
3   SL C   slow cat yan
1   FS H   fast hen Luke
5   SL D   slow dog moe

The nested for-loop appears to find only some of the matches, and is not outputting as intended. Why does this happen? What is the best way to remove each item from mama that contains any of the filterkeywords?

CodePudding user response:

This is a very straightforward place to use a list comprehension to generate a list of items that do not contain any of those keywords.

>>> [f"{i}   {t}   {m}" for i, (t, m) in enumerate(zip(title, mama)) 
...                     if not any(w in m for w in filterkeywords)]
['0   SL C   slow cat Sas', '5   SL C   slow cat yan']
>>>

The generator expression passed to any does the work of checking if any of the keywords are present. We used zip to combine the titles and elements in mama. And enumerate provides the index.

  • Related