我對下面的代碼有什麼區別有疑問。我正在使用matplotlib的動畫類來渲染numpy的數組。在atualizaMundo()
功能,如果我使用mundo[:] = new_mundo[:]
它工作得很好,但如果我使用mundo=new_mundo
數組相等,但動畫不起作用。這裏有什麼不同?matplotlib和numpy的動畫
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
ON = 255
OFF = 0
def criaMundo(N):
return(np.random.choice([ON,OFF],N*N,p=[0.5,0.5]).reshape(N,N))
def atualizaMundo(frameNum,N,mundo,img):
new_mundo = np.random.choice([ON,OFF],N*N,p=[0.5,0.5]).reshape(N,N)
img.set_data(mundo)
mundo[:]=new_mundo[:]
#mundo=new_mundo
return(img,)
def main():
try:
N = 4
mundo = criaMundo(N)
print(mundo)
fig1,ax = plt.subplots()
img = ax.imshow(mundo)
animacao = animation.FuncAnimation(fig1, atualizaMundo, fargs=(N,mundo,img,), blit=True)
plt.show()
except Exception as ex:
pass
if __name__ == '__main__':
try:
main()
except Exception as fk:
pass
雖然https://stackoverflow.com/questions/19676538/numpy-array-assignment-with-copy給出了一些見解,但它並沒有回答爲什麼動畫在兩種情況下工作方式不同的問題 - 這也是由變量的局部範圍。 – ImportanceOfBeingErnest
[Numpy數組賦值與副本]的可能重複(https://stackoverflow.com/questions/19676538/numpy-array-assignment-with-copy) – eyllanesc