python 有没有办法在列表中使用条件元素?[已关闭]

mfuanj7w  于 2022-12-28  发布在  Python
关注(0)|答案(3)|浏览(184)

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
十小时前关门了。
Improve this question
这就是我想要达到的目标:

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...")

'所以我想说的基本上是,如果有人输入"what is your favorite color"或"Tell me about your favorite color"或任何其他必须包含"your","favorite","color"的字符串,代码将打印"It's Black!"然而,如果字符串中缺少这三个关键字中的一个,代码将打印"I don't know what to say ..."
我怎样才能用最少的代码行实现它?因为我正试图建立一个条件聊天机器人类型的应用程序。

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...")
swvgeqrz

swvgeqrz1#

如果按如下方式更改代码:

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...")

我想你会达到目的的

bvhaajcl

bvhaajcl2#

看起来你希望所有的关键字都在问题中;那么正确的代码应该是:

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...")

all的语法是第一条件AND第二条件AND...的快捷方式,而any是第一条件OR...的快捷方式,就像英语口语一样。

x6yk4ghg

x6yk4ghg3#

该代码应该可以帮助您:

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")

只是一个侧记:如果你想用这种方法构建一个聊天机器人,它的规模将是O(k*n)(k=关键字的数量; n=字符串长度)

相关问题