[英]Python- KeyError 'C' on list checking values
I am trying to create a code that assigns values to letters in words, and then spit them back out in pythonm.我正在尝试创建一个代码,将值分配给单词中的字母,然后在 pythonm 中将它们吐回。 This is my code:这是我的代码:
import time
import os
import string
os.system('cls')
values = dict()
for index, letter in enumerate(string.ascii_lowercase):
values[letter] = index + 1
def scramble(letter):
i = 0
phrase = list(letter)
mylist = []
while i < len(phrase):
list.append(values[phrase[i]])
i = i + 1
print(res)
scramble("Crapx")
Well doing this I get the error这样做我得到了错误
Traceback (most recent call last):
File "d:\Code\Python\fibbanaci.py", line 22, in <module>
scramble("Crapx")
File "d:\Code\Python\fibbanaci.py", line 18, in scramble
list.append(values[phrase[i]])
KeyError: 'C'
PS D:\Code\Python>
Does anyone know a fix for this?有谁知道解决这个问题?
The dictionary values map string.ascii_lowercase letters to index + 1. It has no key with upper case letters.字典值 map string.ascii_lowercase letters to index + 1. 它没有带有大写字母的键。 Infact, you could do,事实上,你可以这样做,
def scramble(letter):
i = 0
phrase = list(letter.lower())
mylist = []
while i < len(phrase):
mylist.append(values[phrase[i]])
i += 1
print(phrase)
or;或者; Even though the values dictionary in the global namespace, as a habit, it is good to introduce variables which will be used inside the function (compound structure) as parameters to the function.即使全局命名空间中的值字典,作为一种习惯,最好引入将在 function(复合结构)中使用的变量作为 function 的参数。
import time
import os
import string
os.system('cls')
values = {letter: index for index, letter in enumerate(string.ascii_lowercase, 1)}
def scramble(letter, values):
print [values[char] for char in letter.lower()]
scramble("Crapx", values)
Your dictionary doesn't have uppercase keys.您的字典没有大写键。 You can use string.ascii_letters
instead of string.ascii_lowercase
.您可以使用string.ascii_letters
而不是string.ascii_lowercase
。
import time
import os
import string
os.system('cls')
values = dict()
for index, letter in enumerate(string.ascii_letters):
values[letter] = index + 1
def scramble(letter):
i = 0
phrase = list(letter)
mylist = []
while i < len(phrase):
mylist.append(values[phrase[i]])
i = i + 1
print(mylist)
scramble("Crapx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.