I was coding a discord bot and realized I had difficulty parsing messages. I ended up using a double for loop (yuck). What can I do to optimize this code? (this is a far more straightforward version of the code)
string = "His name is food"
list = ["food", "numbers"]
parsed_string = string.split(" ")
print(parced_string)
for i in parsed_string:
for x in list:
if i == x:
print("stop")
How do I optimize this bit of code?
CodePudding user response:
string = "His name is food"
list = ["food", "numbers"]
parsed_string = string.split(" ")
print(parsed_string)
for i in parsed_string:
if i in list:
print("stop")
CodePudding user response:
For a long list of keywords, prefer a dictionary.
string = "His name is food"
list = {"food": None, "numbers": None]
parsed_string = string.split(" ")
print(parsed_string)
for i in parsed_string:
if i in list:
print("stop")
CodePudding user response:
string = "His name is food"
mylist = ["food", "numbers"]
if set(string.split()).intersection(mylist):
print("stop")
or
if not set(string.split()).isdisjoint(mylist):
print("stop")