简体   繁体   中英

Is there any way to use conditional elements in a list?

This is what I want to achieve:

text = input("Type here: ")
reply = ["favorite" and "your" and "color"]
if any(item in text for item in reply):
  print("It's Black!)
else:
  print("I don't know what to say...")

` So what basically I'm saying is, if someone types "what is your favorite color" or "Tell me about your favorite color" or any other string that must contain "your", "favorite", "color", The code will print "It's Black," However, if one of the three keywords are missing in the string. the code will print "I don't know what to say..."

How can I achieve it with minimum lines of code? because I'm trying to build a conditional chat bot type application.

text = input("Type here: ")
reply = ["favorite" and "your" and "color"]
if any(item in text for item in reply):
   print("It's Black!)
else:
   print("I don't know what to say...")

if you change your code as below:

text = input("Type here: ")
reply = ["favorite", "your", "color"]
if any(item in text for item in reply):
    print("It's Black!")
else:
    print("I don't know what to say...")

I think you will achieve your goal

It seems you want ALL the keywords to be in the question; then some correct code would be:

text = input("Type here: ")
reply = ["favorite", "your", "color"]
if all(item in text for item in reply):
  print("It's Black!")
else:
  print("I don't know what to say...")

The syntax of all is a shortcut for 1st condition AND 2nd condition AND..., while any is a shortcut for 1st condition OR... , just like in spoken English actually.

The code should help you:

i = input("Type: ").lower()
key_words = ["color", "favorite", "your"]
matches = True
for key_word in key_words:
    if not i.count(key_word):
        matches = False
if matches:
    print("It's black")
else:
    print("I don't get it")

Just a side note: If you want to build a chatbot with this method it will scale with O(k*n) (k=number of keywords;n=length of string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM