将用户定义的函数应用于python中的列表列表

2024-04-26 11:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,其中我希望返回每个列表中与特定关键字匹配的字符串的内容

这是原始列表:

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

要应用此关键字搜索:

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

期望的结果:

list_refine = [['summary of the'], ['reveals a lot', 'juniper relationship']]

到目前为止,我有适用于单个列表的代码,但我不知道如何查看所有列表。 下面是一个列表的代码:

string1 = list_orig
substr1 = keywords

def Filter(string, substr): 
    return [str for str in string if
             any(sub in str for sub in substr)] 

print(Filter(string1, substr1))

以下是1个列表的结果:

['summary of the']

我研究了很多方法来循环列表。这里有一次尝试

for item in string3:
     new.append([])
     for item in items:
        item = Filter(string1, substr1)
        new[-1].append(item)
item

刚拿到一张空白名单 谢谢大家!感谢:)


Tags: ofthein列表for关键字summaryfilter
2条回答

您可以使用for循环遍历列表,使用另一个for循环遍历项目和关键字,如下所示

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

list_refine = []

for l_inner in list_orig:
    l_out = []
    for item in l_inner:
        for word in keywords:
            if word in item:
                l_out.append(item)
    list_refine.append(l_out)
print(list_refine) # [['summary of the'], ['reveals a lot', 'juniper relationship']]

这里有一个没有显式循环的替代解决方案

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

def contains_keyword(sentence):
    keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']
    return any([(kw in sentence) for kw in keywords])

list_refine = [
    (sentence for sentence in lst if contains_keyword(sentence))
    for lst in list_orig
]

相关问题 更多 >