【问题标题】:Iterate through python list and extract all matching strings found in a second list遍历 python 列表并提取在第二个列表中找到的所有匹配字符串
【发布时间】:2020-10-22 18:57:21
【问题描述】:

我想遍历我的“匹配”列表中的每个元素并提取该关键字出现的所有字符串 - 它可以是大写或小写:

请有人告诉我哪里出错了?

我尝试过的代码是:

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

谢谢

【问题讨论】:

  • 您可以使用生成器申请any()any(m.lower() in i.lower() for m in match)

标签: python list loops for-loop


【解决方案1】:

您可以使用以下代码来归档您想要的结果:

>>> 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 条目,您可以存档相同的结果(如果这很重要,请按不同的顺序):

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

【讨论】:

  • 谢谢!然而,在我的真实代码中,我得到了错误'float' object has no attribute 'lower'。任何想法为什么会这样?我的数据是数据框中的一列,我将其转换为列表
  • 似乎您的列表之一不仅包含单词(字符串),还包含数字(浮点数)。要处理这种情况,您可以通过调用str 函数将所有值转换为字符串。只需将word.lower() 换成str(word).lower()sentence.lower() 换成str(sentence).lower()
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 2017-03-03
    • 2017-10-21
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多