我是学习Python的初学者,并且已经开始尝试退出,但是我在编写某些代码方面遇到了困难。
本质上,我想编写一个代码来分析每个列表中的单词,以检查单词鹿是否确实存在于哺乳动物列表中,并打印特定的消息。
这是我的尝试:
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
Run Code Online (Sandbox Code Playgroud)
上面的代码在运行时返回:
[99, 111, 119, 99, 97, 116, 112, 105, 103, 109, 97, 110, 119, 111, 109, 97, 110]
[100, 101, 101, 114]
Run Code Online (Sandbox Code Playgroud)
我写上面代码的原因是因为我认为我可以以某种方式创建每个字符的ascii代码列表,然后使用这些列表对ascii代码进行比较,以检查鹿是否确实在哺乳动物列表中
我会建议以下功能:
def check(word, list):
if word in list:
print("The word is in the list!")
else:
print("The word is not in the list!")
Run Code Online (Sandbox Code Playgroud)
这是假设您使用的是Python 3.x,如果您使用的是Python 2,则print语句中不应包含括号
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
21856 次 |
| 最近记录: |