简体   繁体   English

有没有办法在列表中使用条件元素?

[英]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. ` 所以基本上我要说的是,如果有人键入“你最喜欢的颜色是什么”或“告诉我你最喜欢的颜色”或任何其他必须包含“你的”、“最喜欢的”、“颜色”的字符串,代码将打印“It's Black”,但是,如果字符串中缺少三个关键字之一。 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. all的语法是 1st condition AND 2nd condition AND... 的简写,而any是 1st condition OR... 的简写,就像口语一样。

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)附带说明:如果您想使用此方法构建聊天机器人,它将以 O(k*n) 进行扩展(k=关键字数量;n=字符串长度)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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