遍历字符串列表,查找关键字并打印

取两个由字符串组成的列表:


strings = ['hello everyone!', 'how are you doing?', 'are you doing well?', 'are you okay?', 'good, me too.']

searching_for = ['are', 'you', 'doing']

我的目标是搜索strings中的每个项目searching_for并打印包含这些关键字的完整字符串。即,我希望我的输出是:


Output: ['how are you doing?', 'are you doing well?']

请注意,输出只是 中的第 2 和第 3 项strings,它不包含第 4 项。


我不确定为什么这对我来说如此困难,但我认为这归结为我还不够了解 Python。我想让这个足够通用,这样我就可以在一个非常大的字符串列表中搜索我给它的关键字。到目前为止,这是我的解决方案:


def search(*args):

    arg_list = []

    search_for = numpy.append(arg_list, args)

    

    for i in strings:

        for j in search_for:

            if all(j in i) is True:

                print(i)

但这会抛出一个TypeError: 'bool' object is not iterable. 我尝试了上述代码的几个不同的迭代,使用 Python 的内置filter函数和其他一些函数,但我一直被类似的错误所困扰。我也不确定这是否会给我一个列表,我认为它会在终端的新行中吐出结果。


MMTTMM
浏览 109回答 5
5回答

慕斯王

在 python 中有一个叫做list comprehension的东西,它比长循环结构更有效且更容易阅读for。要创建您要查找的列表,这是列表理解的示例:result = [s for s in strings if all(sf in s for sf in searching_for)]# ['how are you doing?', 'are you doing well?']它按照它所说的那样做,在我看来是直截了当的:创建一个列表(括号)s变量中的字符串strings如果可以找到sf变量的所有字符串searching_fors

幕布斯7119047

all(or any) 将尝试遍历它的输入;and Trueor False(作为 的结果j in i)不是可迭代的。这是导致TypeError:all(True)# TypeError: 'bool' object is not iterable相反,让你的内循环更简单:def search(*args):    arg_list = []    search_for = numpy.append(arg_list, args)        for i in strings:        if all(j in i for j in search_for):            print(i)或者更简单:def search(args):    for i in strings:        if all(j in i for j in args):            print(i)输出:search(searching_for)# how are you doing?# are you doing well?请注意,您不需要all(...) is Truesince allwould already have returned either TrueorFalse

人到中年有点甜

strings = ['hello everyone!', 'how are you doing?', 'are you doing well?', 'are you okay?', 'good, me too.']keywords = ['are', 'you', 'doing']for s in strings:    for word in s.split():        if word in keywords:            print(s)             break

幕布斯6054654

尝试这个:for st in strings:    if set(searching_for).issubset(set(st[:-1].split())):        print(st)

慕娘9325324

你可以试试print([i for i in strings if all([s in i for s in searching_for])])输出['how are you doing?', 'are you doing well?']此列表理解将检查searching_for列表中的所有单词是否在每个句子中strings,如果是,它将打印该句子。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python