繁体   English   中英

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

[英]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")

输出:(我不想要这个)

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' 'black'list_1的项目(或其子字符串)中,我想打印它;如果list_1的字符串值中既不存在'blue'也不存在 'black',我想打印not found 但是我的代码不起作用。 我希望我的输出看起来像这样:

black
not found
black
blue
black
blue
not found
blue
black

因为我们这里有 strigs,所以使用 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

更新您的代码:

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

您还可以使用列表理解

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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