我正在制作一个类似AI的程序。我开始对该项目进行编码,但遇到了障碍。我想获取一个单词列表,然后在返回布尔值时检查给定的字符串是否在列表内。我的代码看起来像这样...
listofhellos = ['hello', 'hi', 'hey!!!']
if listofhellos.lower() == 'hello':
# This checks if string 'hello' is in listofhellos
print('Hey, how are you?')
# if it is in the list then print out a response
谢谢!
这是解决方法:
listofhellos = ['hello', 'hi', 'hey!!!']
check = "Hello"
if check.lower() in listofhellos:
print('Exists')
else:
print("Not exists")
您可以尝试-
if 'hello' in map(str.lower, ['hello', 'hi', 'Hey!!!']):
或
return 'hello' in map(str.lower, ['hello', 'hi', 'Hey!!!']):```
您可能想将any()
内置功能与any()
(实际上是the Python 'list comprehension')结合使用:
generator expression
这将按顺序遍历列表中的每个项目,对其进行测试,并在验证测试的第一项中返回if any(item.lower() == 'hello' for item in listofhellos):
print('hey, how are you?')
。