检查一个单词是否在 Python 的列表中 [英] Checking if a word is in a list in Python

查看:38
本文介绍了检查一个单词是否在 Python 的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am beginner in learning Python and have been practicing quit a bit however I have been having difficulties with a certain code I would like to write.

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

Essentially, I want to write a code which would analyse the word(s) in each list to check whether the word deer is indeed in the list mammals and print a certain message.

这是我的尝试:

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

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

The code above, when run, returns:

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

我写上面代码的原因是因为我认为我可以以某种方式创建每个字符的 ascii 代码列表,然后使用这些列表来比较 ascii 代码以检查鹿是否确实在列表中哺乳动物

Reason why I wrote the code above was because I thought I could somehow create a list of the ascii codes of each character and then use those lists to do my comparison of the ascii codes as to check whether deer is indeed in the list of mammals

推荐答案

我建议使用以下功能:

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,那么您的打印语句中不应有括号

This is assuming you're using Python 3.x, if you're using Python 2, then there shouldn't be parenthesis in your print statements

希望这会有所帮助!

这篇关于检查一个单词是否在 Python 的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆