Python Search Multiple Word In List
I have Python list like this: ['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher'] Now I want to search wi
Solution 1:
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)
Solution 2:
As Adrian Shum said, your input gives you a single string. You need to split it up first before feeding it to your function
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)
Solution 3:
You can try this
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)
output:
input keywords: sales teacher
salesperson
sales manager
schoolteacher
mathematics teacher
Solution 4:
You can use the find() method. This should work for you:
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)
The above code was for readability and understandability. However, it can be compressed into a nice one-liner using list comprehensions like this:
x = [y for y in lis for string in str1 if y.find(string) != -1]
Both do the same thing and give the output as this
['salesperson', 'sales manager', 'schoolteacher', 'mathematics teacher']
Good Luck!
Post a Comment for "Python Search Multiple Word In List"