gpt4 book ai didi

Python在列表中搜索多个单词

转载 作者:行者123 更新时间:2023-11-28 21:33:16 24 4
gpt4 key购买 nike

我有这样的Python列表:

['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']

现在我想使用列表中的多个关键字进行搜索,例如:

当我尝试输入关键字老师销售

input keywords: teacher sales

它应该返回这样的结果:

  • 学校老师
  • 数学老师
  • 销售人员
  • 销售经理

到目前为止,我已经编写了这样的代码:

job_list = ['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']

def search_multiple_words(search_words):
search_words = [search_words]

for line in job_list:
if any(word in line for word in search_words):
print(line)

search_words = input("input keywords: ")
search_multiple_words(search_words)

但它只在我输入一个关键字时起作用,而不是像我上面给出的示例那样输入多个关键字。

那么,如何做到这一点..?

最佳答案

job_list = ['assistant manager', 'salesperson', 'doctor', 'production manager',
'sales manager', 'schoolteacher', 'mathematics teacher']


def search_multiple_words(search_words):
search_words = search_words.split(' ')

out = [s for s in job_list if any(xs in s for xs in search_words)]
print(out)


search_words = input("input words: ")
search_multiple_words(search_words)

关于Python在列表中搜索多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com