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

标签 python python-2.7

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

基本上,我想编写一个代码来分析每个列表中的单词,以检查单词 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,那么你的打印语句中不应该有括号

希望这对您有所帮助!

关于python - 检查一个单词是否在 Python 列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316425/

相关文章:

使用 Docker 的 Python 脚本沙箱

python - 正则表达式匹配 Python 函数调用

python - 获取 Pandas 组内满足条件的值的百分比

python - DAG的并行处理

Python virtualenv setuptools 包问题

python - Django all-auth 删除在注册表单中两次询问密码

python - 使用 Django 中现有的列值更新列的值

python - 在多个文本文件中搜索两个字符串?

python - 为 python 独立可执行文件创建插件

python - 跳到字典中的下一项