繁体   English   中英

检查一个单词是否在 Python 的列表中

[英]Checking if a word is in a list in Python

我是学习 Python 的初学者,并且一直在练习退出,但是我在编写我想编写的某些代码时遇到了困难。

本质上,我想编写一个代码来分析每个列表中的单词,以检查单词 deer 是否确实在 mammals 列表中并打印特定消息。

这是我的尝试:

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 代码以检查 deer 是否确实在哺乳动物列表中

我会建议以下功能:

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

这假设你使用的是Python 3.x,如果你使用的是Python 2,那么你的print语句中不应该有括号

希望这可以帮助!

欢迎使用Python! 这种事情在这里非常重要。 你需要的是什么

print('deer' in myMammals)
>> True
wordchecker = input("please enter your sentence ->")
wordfinder = input("please enter the word you want to find in your sentence -> ")
if wordfinder in wordchecker:
    print(f"_{wordchecker}_ has _{wordfinder}_ in it")
else:
    print(f"_{wordchecker}_ doesn't have _{wordfinder}_ in it")

暂无
暂无

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

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