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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42316425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:33:31  来源:igfitidea点击:

Checking if a word is in a list in Python

pythonpython-2.7

提问by Hobbes

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.

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

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.

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

Here was my attempt:

这是我的尝试:

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]

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

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

回答by Sishaar Rao

I would suggest a function along the following:

我会建议以下功能:

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

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 3.x,如果您使用的是 Python 2,那么您的打印语句中不应有括号

Hope this helps!

希望这可以帮助!

回答by Anomitra

Welcome to Python! This sort of thing is really elementary here. What you need is

欢迎使用 Python!这种事情在这里真的很基本。你需要的是

print('deer' in myMammals)
>> True