代入公式触发TypeError: 'float' object is not callable问题排查
问题原因
- 你写的
travtimes = adj属于浅引用,没有新建独立数组,第一次循环执行时会直接修改原adj矩阵里存储的lambda函数为计算后的浮点数,后续循环到已经被替换的位置时,就会出现「尝试调用浮点数」的报错 - numpy的
astype方法不是原地修改操作,你现有代码里的travtimes.astype(dtype=object)、flows.astype(dtype=int)执行后没有赋值给变量,对应转换逻辑完全不生效 - adj矩阵初始化时填充的默认值是
np.inf(浮点数类型),这些没有对应lambda函数的位置直接执行调用操作也会触发报错
修复方案
修改循环逻辑,先判断当前位置是不是可调用的函数再执行计算,同时修正矩阵引用、类型转换的问题即可,修复后代码如下:
import numpy as np edges = np.array([[0, 1, lambda N: N/100], [0, 2, lambda N: 45], [1, 3, lambda N: 45], [2, 3, lambda N: N/100]], dtype=object) nodes = np.unique(edges[:,0:2]) num_nodes = len(nodes) adj = np.full((num_nodes, num_nodes), np.inf, dtype=object) nodelen = len(edges) for x in range(nodelen): edge = edges[x,:] first, second, func = edge adj[int(first), int(second)] = func flows = np.zeros((num_nodes, num_nodes), dtype=int) # 新建独立的travtimes数组,避免直接修改原adj矩阵 travtimes = adj.copy() adjlen = len(adj) y=0 while y < adjlen: for x in range(adjlen): # 仅对可调用的lambda函数执行计算 if callable(travtimes[x,y]): travtimes[x,y] = travtimes[x,y](flows[x,y]) y = y+1 print(travtimes)
运行输出
[[inf 0.0 45 inf] [inf inf inf 45] [inf inf inf 0.0] [inf inf inf inf]]
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

