TypeError:'dict'对象不可调用

Enc*_*iby 39 python dictionary

我正在尝试循环输入字符串的元素,并从字典中获取它们.我究竟做错了什么?

number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 }
input_str = raw_input("Enter something: ")
strikes = [number_map(int(x)) for x in input_str.split()]
Run Code Online (Sandbox Code Playgroud)
strikes  = [number_map(int(x)) for x in input_str.split()]
TypeError: 'dict' object is not callable
Run Code Online (Sandbox Code Playgroud)

jen*_*ena 48

在给定密钥的情况下访问字典的语法是number_map[int(x)].number_map(int(x))实际上是一个函数调用但由于number_map不是可调用的,因此会引发异常.


小智 18

使用方括号访问字典.

strikes = [number_map[int(x)] for x in input_str.split()]
Run Code Online (Sandbox Code Playgroud)


小智 12

您需要使用它[]来访问字典的元素.不()

  number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 }
input_str = raw_input("Enter something: ")
strikes = [number_map[int(x)] for x in input_str ]
Run Code Online (Sandbox Code Playgroud)


Ole*_*pin 9

罢工 = [number_map [ int(x) ] for x in input_str.split()]

您可以使用这些括号从dict 中获取一个元素[],而不是这些()


Seb*_*ino 6

strikes  = [number_map[int(x)] for x in input_str.split()]
Run Code Online (Sandbox Code Playgroud)

使用方括号来浏览词典.


det*_*tly 5

您需要使用:

number_map[int(x)]
Run Code Online (Sandbox Code Playgroud)

注意方括号!