def parse_neighbors(neighbors, vars):
"""Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping
regions to neighbors. The syntax is a region name followed by a ':'
followed by zero or more region names, followed by ';', repeated for
each region name. If you say 'X: Y' you don't need 'Y: X'.
>>> parse_neighbors('X: Y Z; Y: Z')
{'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']}
"""
dict = defaultdict([])
for var in vars:
dict[var] = []
specs = [spec.split(':') for spec in neighbors.split(';')]
for (A, Aneighbors) in specs:
A = A.strip();
dict.setdefault(A, [])
for B in Aneighbors.split():
dict[A].append(B)
dict[B].append(A)
return dict
当我从AIMA书中调用此片段时,如下所示:
neigh = parse_neighbors(constr,vars)
其中constr是String,vars是邻居,
我收到以下错误: dict = defaultdict([]) TypeError:第一个参数必须是可调用的
请帮助!!!
答案 0 :(得分:1)
您需要使用:
d = defaultdict(list)
而不是:
d = defaultdict([])
正如错误消息所示:
TypeError:第一个参数必须是可调用的
[]
不是可调用的,它是一个空列表。
>>> []()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
list
是可调用的。注意你打电话时会发生什么:
>>> list()
[]
>>>