在Python中检查单词是否在列表中

2024-05-12 00:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我是学习Python的初学者,一直在练习quit,但是我在编写特定的代码时遇到了困难。

本质上,我想写一个代码来分析每个列表中的单词,以检查单词deer是否真的在列表中哺乳动物,并打印出特定的消息。

我的尝试是:

myMammals = ['cow', 'cat', 'pig', 'man', 'woman']
ASCIIcodes = []
ASCII = x
for mammal in myMammals:
    for letter in mammal:
        x = ord(letter)
        ASCIIcodes.append(x)
print ASCIIcodes

animal = ['deer']
ASCIIcodes2 = []
ASCIIvalue = x
for word in animal:
    for letter in word:
        x = ord(letter)
        ASCIIcodes2.append(x)
print ASCIIcodes2

上面的代码在运行时返回:

[99, 111, 119, 99, 97, 116, 112, 105, 103, 109, 97, 110, 119, 111, 109, 97, 110]
[100, 101, 101, 114]

我之所以写上面的代码是因为我认为我可以创建一个每个字符的ascii码列表,然后用这些列表来比较ascii码,以检查鹿是否真的在哺乳动物的列表中


Tags: 代码in列表for单词printletterappend
2条回答

我建议按以下方式执行一项功能:

def check(word, list):
    if word in list:
        print("The word is in the list!")
    else:
        print("The word is not in the list!")

假设您使用的是Python3.x,如果您使用的是Python2,那么打印语句中不应该有括号

希望这有帮助!

欢迎来到Python!这类事情在这里是很基本的。你需要的是

print('deer' in myMammals)
>> True

相关问题 更多 >