我有一些嵌套函数,我试图用以下公式求出某个事件发生的总次数:
if C[city_cell_x][city_cell_y] == 1:
cityCount +=1
但由于这是一个函数:
# Animate
fig = plt.figure()
plt.axis("on")
ims = []
for t in range(totalTime):
print(str(r), " Time = " + str(t))
ims.append((plt.imshow(C, cmap="Accent"),))
C = mapRun(C)
if C[city_cell_x][city_cell_y] == 1:
cityCount +=1
im_ani = animation.ArtistAnimation(
fig, ims, interval=interval, repeat_delay=3000, blit=True
)
# Save the animation?
if save:
print("Saving...")
im_ani.save(("Repeat" + str(r) + ".html"), writer="html", fps=60, dpi=75)
然后我循环,它不是没有成功计数,只是在结尾返回零,它是提高“cityCount referenced before assignment”,即使它是在代码开头引用的(函数之外)
我可以提供完整的代码,如果这更容易
看起来问题可能是所描述的here。你知道吗
如果您在函数外部创建了
cityCount
,并且正在尝试在函数内部赋值,那么您将得到一个新的局部变量。你知道吗如果
if
语句从不为true,cityCount
从不递增,但代码运行良好。 如果if
语句为true,则会出现错误,因为没有要添加到的本地cityCount
。你知道吗解决方法是在函数的开头添加
global cityCount
。你知道吗相关问题 更多 >
编程相关推荐