如何在每个项目上使用函数检查字符串是否在列表中(python3)[duplicate]

问题描述 投票:0回答:3

我正在制作一个类似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

谢谢!

python string
3个回答
-1
投票

这是解决方法:

listofhellos = ['hello', 'hi', 'hey!!!']
check = "Hello"
if check.lower() in listofhellos:
    print('Exists')
else:
    print("Not exists")

0
投票

您可以尝试-

if 'hello' in map(str.lower, ['hello', 'hi', 'Hey!!!']):

return 'hello' in map(str.lower, ['hello', 'hi', 'Hey!!!']):```

-1
投票

您可能想将any()内置功能与any()(实际上是the Python 'list comprehension')结合使用:

generator expression

这将按顺序遍历列表中的每个项目,对其进行测试,并在验证测试的第一项中返回if any(item.lower() == 'hello' for item in listofhellos): print('hey, how are you?')

© www.soinside.com 2019 - 2024. All rights reserved.