[英]Python - Iterate through a list of strings and group partial matching strings
[英]Iterate through python list and extract all matching strings found in a second list
我想遍历“匹配”列表中的每个元素并提取出现此关键字的所有字符串 - 它可以是大写或小写:
请有人让我知道我哪里出错了吗?
我尝试过的代码是:
match=['FUN','HAPPY','FLORAL', 'alpha','12133','water12']
data=['the fun we are', 'hello there', 'Happy today is the case','112133 is it', 'FLORAL is my fave']
lst=[]
for i in match:
for j in data:
if i.lower() in j.lower():
lst.append(j)
else:
lst.append('not found')
所需的输出:
lst=['the fun we are','Happy today is the case','112133 is it' ,'FLORAL is my fave']
谢谢
您可以使用以下代码来存档您想要的结果:
>>> match=['FUN','HAPPY','FLORAL', 'alpha','12133','water12']
>>> data=['the fun we are', 'hello there', 'Happy today is the case','112133 is it', 'FLORAL is my fave']
>>> lst = [sentence for sentence in data if any(word.lower() in sentence.lower() for word in match)]
>>> lst
['the fun we are', 'Happy today is the case', '112133 is it', 'FLORAL is my fave']
如果您删除代码中的 else 部分,则not found
添加not found
条目,您可以存档相同的结果(如果这很重要,请按不同的顺序):
>>> lst=[]
>>> for i in match:
... for j in data:
... if i.lower() in j.lower():
... lst.append(j)
...
>>> lst
['the fun we are', 'Happy today is the case', 'FLORAL is my fave', '112133 is it']
Querenker 的先前回答很好地总结了这些方法。 但是,如果您想保留一个附加功能(这似乎是您打算包括的),当列表之间没有一致时,将返回"not found"
,这里有一个替代方案:
lst=[]
for i in match:
for j in data:
if i.lower() in j.lower():
lst.append(j)
else:
if lst == []:
print('not found')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.