python - "Not in list" error while using intersection -


i trying find match between 2 lists code:

 def matching(text, symples, half2):   word in text:     find = set(symples).intersection(word)   indexnum = symples.index(find)  print(indexnum)  print(find) 

i succeeded in finding match between them. need find index number of matching word in list , when try error message word not found in list.

i tried print matching word between 2 lists find , printed brackets ( {} or [] ).

are brackets reason there no match found in list?

there are couple reasons code isn't working , right on brackets being 1 reason.

the line find = set(symples).intersection(word) returns , assigns set variable find. later, when try find index of find, not found because set not found in list.

for example:

symples = ['1','2','3'] word = '1' find = set(symples).intersection(word) # find = {'1'} indexnum = symples.index(find)         # not found because {'1'} not in list 

to fix this, loop through intersection set:

find = set(symples).intersection(word) f in find:     indexnum = symples.index(f)     print(indexnum)     print(f) 

there bunch of problems indentation in code. loop keeps running, find ever has set intersection of last word. if want print out each one, make sure have right indentation. here example previous errors fixed well:

def matching(text, symples, half2):     word in text:         find = set(symples).intersection(word)         f in find:             indexnum = symples.index(f)             print(indexnum)             print(f) 

however, there better ways implement this...

  1. only take intersection once.

    there's no reason loop through text , take intersection each time. take intersection of 2 lists right away.

    def matching(text, symples, half2):     find = set(symples).intersection(text)     f in find:         indexnum = symples.index(f)         print(indexnum)         print(f) 
  2. loop through 1 list , check if each word in other list.

    def matching(text, symples, half2):     word in symples:         if word in text:             indexnum = symples.index(word)             print(indexnum)             print(word) 
  3. loop through 1 list , check if each word in other list, while keeping track of index.

    def matching(text, symples, half2):     indexnum, word in enumerate(symples):         if word in text:             print(indexnum)             print(word) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -