Python 计数问题

Python counting issue

我有一些嵌套函数,我正在尝试使用以下方法计算某事发生的总次数:

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 语句永远不会为真,则 cityCount 永远不会递增,但代码运行正常。 如果 if 语句为真,则会出现错误,因为没有要添加到的本地 cityCount

解决方案是在函数的开头添加 global cityCount