Python在列表中搜索多个单词

时间:2019-02-22 01:34:25

标签: python arrays python-3.x

我有这样的Python列表:

[].find

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

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

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

它应该返回如下结果:

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

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

input keywords: teacher sales

但是当我输入一个关键字而不是上面我给出的示例的多个关键字时,它才有效。

那么,怎么做..?

4 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

您可以使用find()方法。这应该为您工作:

lis=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
str1 = ["teacher", "sales"]
x=[]
for y in lis:
    for string in str1:
        if y.find(string) != -1:
            x.append(y)

上面的代码用于可读性和可理解性。但是,可以使用以下列表理解将其压缩成一个很好的单行代码:

x = [y for y in lis for string in str1 if y.find(string) != -1]

两者都做同样的事情,并给出如下输出结果

  

[“销售员”,“销售经理”,“学校老师”,“数学”   老师']

祝你好运!

答案 2 :(得分:1)

正如Adrian Shum所说,您的输入为您提供了一个字符串。您需要先对其进行拆分,然后再将其提供给函数

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

def search_multiple_words(search_words):
    # Not neecssary anymore as you're feeding a list
    # 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: ").strip().split()
search_multiple_words(search_words)

答案 3 :(得分:1)

您可以尝试

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: ").split(' ')
for w in search_words:
    search_multiple_words(w)

输出:

input keywords: sales teacher
salesperson
sales manager
schoolteacher
mathematics teacher