Python 在循环结束时覆盖数组

Python 在循环结束时覆盖数组,python,for-loop,overwrite,Python,For Loop,Overwrite,我在for循环中将数据写入2d数组时遇到问题。如果在循环中打印/绘图,则值似乎正常。如果在循环外打印,则数组中的所有行都相等。见附件截图。有人对如何防止覆盖数组中的值提出建议吗 import matplotlib.pyplot as plt import math as mt import numpy as np I0=1 # L=5 #[m] distance from slit screen to the observation screen w=[668, 613, 575, 540,

我在for循环中将数据写入2d数组时遇到问题。如果在循环中打印/绘图,则值似乎正常。如果在循环外打印,则数组中的所有行都相等。见附件截图。有人对如何防止覆盖数组中的值提出建议吗

import matplotlib.pyplot as plt
import math as mt
import numpy as np

I0=1 #
L=5 #[m] distance from slit screen to the observation screen
w=[668, 613, 575, 540, 505, 470, 425] #[nm] wavelengths
b=14 #[um] slit width

n=10 #length of array

x = np.linspace(-2*mt.pi,2*mt.pi, n)

bet=[[0.0]*n]*len(w) #beta
Ip=[[0.0]*n]*len(w) #intensity

fig,ax=plt.subplots()
ax2=ax.twinx()

# for 7 different wavelenths
for j in range(len(w)):
    # write to array
    for i in range(n):
        bet[j][i]=mt.pi*b/w[j]*mt.sin(x[i])
        Ip[j][i]=I0*(mt.sin(bet[j][i])/bet[j][i])**2
    ax.plot(x,bet[j])
    ax2.plot(x,Ip[j])
    print(Ip[j]) 
plt.show()

#to compare with the print within the loop
for k in range(len(w)):
    print(Ip[k]) #all rows is equal
打印/打印:


这些行有问题:

bet=[[0.0]*n]*len(w) #beta
Ip=[[0.0]*n]*len(w) #intensity
这是因为,当您将列表列表相乘时,行将指向完全相同的列表

您应该将这两行更改为:

bet=[[0.0]*n for _ in range(len(w))] #beta
Ip=[[0.0]*n for _ in range(len(w))] #intensity

您有以下行的问题:

bet=[[0.0]*n]*len(w) #beta
Ip=[[0.0]*n]*len(w) #intensity
这是因为,当您将列表列表相乘时,行将指向完全相同的列表

您应该将这两行更改为:

bet=[[0.0]*n for _ in range(len(w))] #beta
Ip=[[0.0]*n for _ in range(len(w))] #intensity

谢谢你快速解决我的问题。谢谢你快速解决我的问题。