TypeError:'dict' 对象不可调用
- 2025-03-20 08:46:00
- admin 原创
- 54
问题描述:
我正在尝试循环遍历输入字符串的元素,并从字典中获取它们。我做错了什么?
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()]
strikes = [number_map(int(x)) for x in input_str.split()]
TypeError: 'dict' object is not callable
解决方案 1:
通过给定键来访问字典的语法是使用方括号:
number_map[int(x)]
^ ^
number_map(int(x))
(带括号)实际上是一个函数调用,但由于number_map
不可调用,因此会引发异常。
解决方案 2:
使用方括号访问字典。
strikes = [number_map[int(x)] for x in input_str.split()]
解决方案 3:
您需要使用[]
来访问字典的元素。不是()
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 ]
解决方案 4:
strikes = [number_map [ int(x) ] for x in input_str.split()]
使用这些括号而不是这些从字典中获取元素。[]
()
解决方案 5:
strikes = [number_map[int(x)] for x in input_str.split()]
使用方括号来探索字典。
解决方案 6:
您需要使用:
number_map[int(x)]
注意方括号!
解决方案 7:
更实用的方法是使用dict.get
input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))
可以观察到转换有点笨拙,最好使用函数组合的抽象:
def compose2(f, g):
return lambda x: f(g(x))
strikes = list(map(compose2(number_map.get, int), input_str.split()))
Example:
list(map(compose2(number_map.get, int), ["1", "2", "7"]))
Out[29]: [-3, -2, None]
显然,在 Python 3 中,你会避免显式转换为。 Python 中函数组合的更通用方法可以在这里list
找到。
(备注:我是从Udacity 的计算机程序设计课上过来写的:)
def word_score(word):
"The sum of the individual letter point scores for this word."
return sum(map(POINTS.get, word))
解决方案 8:
它是number_map[int(x)]
,你试图用一个参数实际调用地图
解决方案 9:
使用方括号:--> number_map[int(x)]
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()]
***You need to use [] with dictionaries. Use square brackets***
strikes = [number_map[int(x)] for x in input_str.split()]
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD