Python计数问题

2024-06-25 05:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些嵌套函数,我试图用以下公式求出某个事件发生的总次数:

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”,即使它是在代码开头引用的(函数之外)

我可以提供完整的代码,如果这更容易


Tags: 函数cityifsavefigcellpltims
1条回答
网友
1楼 · 发布于 2024-06-25 05:35:31

看起来问题可能是所描述的here。你知道吗

如果您在函数外部创建了cityCount,并且正在尝试在函数内部赋值,那么您将得到一个新的局部变量。你知道吗

如果if语句从不为true,cityCount从不递增,但代码运行良好。 如果if语句为true,则会出现错误,因为没有要添加到的本地cityCount。你知道吗

解决方法是在函数的开头添加global cityCount。你知道吗

相关问题 更多 >