为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MMTTMM 2023-02-22 19:08:48
取两个由字符串组成的列表: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函数和其他一些函数,但我一直被类似的错误所困扰。我也不确定这是否会给我一个列表,我认为它会在终端的新行中吐出结果。
查看完整描述

5 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

在 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


查看完整回答
反对 回复 2023-02-22
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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


查看完整回答
反对 回复 2023-02-22
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

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


查看完整回答
反对 回复 2023-02-22
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

尝试这个:


for st in strings:

    if set(searching_for).issubset(set(st[:-1].split())):

        print(st)


查看完整回答
反对 回复 2023-02-22
?
慕娘9325324

TA贡献1783条经验 获得超4个赞

你可以试试

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,如果是,它将打印该句子。


查看完整回答
反对 回复 2023-02-22
  • 5 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信