繁体   English   中英

类型错误:'dict' object 不可调用

[英]TypeError: 'dict' object is not callable

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

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

给定键访问字典的语法是number_map[int(x)] number_map(int(x))实际上是一个 function 调用,但由于number_map不是可调用的,因此会引发异常。

使用方括号访问字典。

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

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

  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 ]
strikes  = [number_map[int(x)] for x in input_str.split()]

使用方括号来浏览字典。

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

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

你需要使用:

number_map[int(x)]

注意方括号!

它是number_map[int(x)] ,你试图用一个参数实际调用 map

把“()”改成“[]”因为“()”是用来表示函数的

更实用的方法是使用dict.get

input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))

可以观察到转换有点笨拙,最好使用function 组合的抽象:

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 中,您将避免显式转换为list 可以在此处找到 Python 中 function 组合的更通用方法。

(备注:我是从 Udacity的计算机程序设计class 来的,写的:)

def word_score(word):
    "The sum of the individual letter point scores for this word."
    return sum(map(POINTS.get, word))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM