我正在尝试制作一个程序,使用存储在字典中的值来转换每个字母,将用户输入的 5 个字母字符串转换为 float 。这是我的代码:
kvalues = {"a":1.01, "b":1.02, "c":1.03, "d":1.04, "e":1.05, "f":1.06, "g":1.07, "h":1.08, "i":1.09, "j":1.10, "k":1.11, "l":1.12, "m":1.13, "n":1.14, "o":1.15, "p":1.16, "q":1.17, "r":1.18, "s":1.19, "t":1.20, "u":1.21, "v":1.22, "w":1.23, "x":1.24, "y":1.25, "z":1.26}
def convert_key(key):
#converts the key into a float using the values stored in kvalues
k1 = float(kvalues.get(key[0]))
k2 = float(kvalues.get(key[1]))
k3 = float(kvalues.get(key[2]))
k4 = float(kvalues.get(key[3]))
k5 = float(kvalues.get(key[4]))
print k1 + k2 + k3 + k4 + k5
convert_key(raw_input (Please enter a key:))
当我运行程序时,出现此错误:“TypeError: 'builtin_function_or_method' object has no attribute 'getitem'”。真正令人困惑的部分是当我通过空闲 shell 运行代码时,如下所示:
key = "koala"
kvalues = {"a":1.01, "b":1.02, "c":1.03, "d":1.04, "e":1.05, "f":1.06, "g":1.07, "h":1.08, "i":1.09, "j":1.10, "k":1.11, "l":1.12, "m":1.13, "n":1.14, "o":1.15, "p":1.16, "q":1.17, "r":1.18, "s":1.19, "t":1.20, "u":1.21, "v":1.22, "w":1.23, "x":1.24, "y":1.25, "z":1.26}
k1 = float(kvalues.get(key[0]))
print k1
效果非常好!有谁知道这里的问题是什么?我是 Python 新手,不太熟悉该语言的细微差别。
这是完整的回溯:
Traceback (most recent call last):
File "K:\Projects\koala.py", line 73, in <module> menu()
File "K:\Projects\koala.py", line 10, in menu encrypt()
File "K:\Projects\koala.py", line 28, in encrypt e_key = convert_key(e_key)
File "K:\Projects\koala.py", line 67, in convert_key k1 = float(kvalues.get(key[0]))
TypeError: 'builtin_function_or_method' object has no attribute 'getitem'
当 print 添加到函数的开头时:
<built-in method lower of str object at 0x0000000002AC7E40>
最佳答案
问题是你在某个地方这样做:
e_key = mystring.lower
当你打算这样做时:
e_key = mystring.lower()
.lower
是一个方法,这意味着它需要像函数一样被调用,所以你需要括号。在第一种方法中,您只需将该方法重新分配给 e_key
变量即可。
关于python - 任何人都可以帮助我解决我在 Python 2.7 中不断遇到的 TypeError 问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303403/