![](/img/trans.png)
[英]python remove element from nested list if it exists in another list +
[英]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.