【问题标题】:Overwrites array in end of loop Python在循环Python结束时覆盖数组
【发布时间】:2021-07-17 19:06:31
【问题描述】:

在 for 循环中将数据写入二维数组时遇到问题。如果我在循环内打印/绘图,则值似乎正常。而如果我在循环外打印,则数组中的所有行都是相等的。请参阅随附的屏幕截图。有人对如何防止覆盖数组中的值提出建议吗?

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

打印/绘图:

【问题讨论】:

    标签: python for-loop overwrite


    【解决方案1】:

    这些行有问题:

    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
    

    【讨论】:

    • 感谢您快速解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2016-06-14
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多