在Python中,如果一个列表中的元素存在于另一个列表中,如何打印它?

smdnsysy  于 2022-12-20  发布在  Python
关注(0)|答案(3)|浏览(172)
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")

输出:(我不想要这个)

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

如果'blue''black'存在于list_1的项(或项的子字符串)中,我想打印'blue''black',如果list_1的字符串值中既不存在'blue'也不存在'black',我想打印not found。但是我的代码不工作。我希望输出如下所示:

black
not found
black
blue
black
blue
not found
blue
black
4nkexdtk

4nkexdtk1#

因为我们在这里遇到了一些问题,所以使用regex是有意义的,如下所示:

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
scyqe7ek

scyqe7ek2#

也可以使用列表解析

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]
ckx4rj1h

ckx4rj1h3#

更新您的代码:

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

相关问题