简体   繁体   中英

How to print an element from one list if it exists in another list in Python?

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 my code is not working. I want my output look like this:

black
not found
black
blue
black
blue
not found
blue
black

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

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")

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM