Home > Back-end >  How to print an element from one list if it exists in another list in Python?
How to print an element from one list if it exists in another list in Python?

Time:12-16

list1 = ['moonlight black','mint cream','electric black','deep blue',
         'black','blue','flowing silver','crystal blue','ink black']
list2 = ["blue","black"]
         
for i in list1:
    for j in list2:
        if j in i:
            print(j)
        else:
            print("not found")

output:  (I don't want this)                               
not found
black
not found
not found
not found
black
blue
not found
not found
black
blue
not found
not found
not found
blue
not found
not found
black

I want to print the 'blue' or 'black' if it exists in( or substring of) item in list_1 , and print 'not found' if neither 'blue or black' exists in the string value of list_1. But in my code is not working. I want my output look like this - required output: black not found black blue black blue not found blue black

CodePudding user response:

you can also use list comprehension

list1 = ['moonlight black','mint cream','electric black','deep blue','black','blue','flowing silver','crystal blue','ink black']
list2 = [print('black') if 'black' in color else print('blue') if 'blue' in color else print('not found') for color in list1]

CodePudding user response:

as we have strigs here it has sence to use regex, like this:

from re import search

for i in list1:
    print(m[0] if (m:=search('|'.join(list2),i)) else 'not found')

>>>
'''
black
not found
black
blue
black
blue
not found
blue
black

CodePudding user response:

update your code:

list1 = ['moonlight black','mint cream','electric black','deep blue',
         'black','blue','flowing silver','crystal blue','ink black']
list2 = ["blue","black"]
         
for i in list1:
    for j in list2:
        if j in i:
            print(j)
            break 
    else:
        print("not found")
  • Related