【问题标题】:building lists of numpy arrays构建 numpy 数组列表
【发布时间】:2021-10-06 02:11:46
【问题描述】:

我有以下代码,它根据从文件中读取的数据构建二维 numpy 数组的列表。

rawLambda = np.loadtxt("LambdaM.dat")
rawchi0 = np.loadtxt("chi0M.dat")

npts = len(rawLambda[:,0])//10000

LambdaList = []
chi0List = []
Lambdatmp = np.zeros((100,100),dtype=complex)
chi0tmp = np.zeros((100,100),dtype=complex)
for i in range(npts):
 for l in range(10000):
  ii = i*10000+l
  l1 = int(rawLambda[ii,3]-1)
  l2 = int(rawLambda[ii,4]-1)
  Lambdatmp[l1,l2] = rawLambda[ii,5] + 1.j*rawLambda[ii,6]
  l1 = int(rawchi0[ii,3]-1)
  l2 = int(rawchi0[ii,4]-1)
  chi0tmp[l1,l2] = rawchi0[ii,5] + 1.j*rawchi0[ii,6]
  
 LambdaList.append(Lambdatmp)
 chi0List.append(chi0tmp)

如果我尝试从 chi0List 中检索单个数组,例如,

for i in range(npts):
 tst = np.sum(chi0List[i])
 print(i,tst)

结果表明列表中的所有数组都与添加的最后一个相同。有人可以告诉我在这里做错了什么吗?!谢谢!

【问题讨论】:

    标签: python arrays numpy append


    【解决方案1】:

    当使用 numpy 或列表时,你应该知道你在复制什么。您附加到列表的数组只是数组的浅表副本。它们都指向同一个数组。在追加时,您应该创建一个副本,以免将指针追加到同一个列表,如

    LambdaList.append(Lambdatmp.copy())
    chi0List.append(chi0tmp.copy())
    

    【讨论】:

      【解决方案2】:

      因为你不创建新列表

      chi0tmp = np.zeros((100,100),dtype=complex)
      

      这会在内存中提供一个您可以就地更改的数组。附加只会在您的列表中删除该数组的视图,该视图会随着每个循环而更改。要解决此问题,请在外部 for 循环中创建临时数组

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 2016-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多