python关于矩阵重复赋值会覆盖的问题

import itertools
import numpy as np
comb = list(itertools.combinations(list(range(regions)), 2))
bands_info = []
coeff = np.zeros([bands, len(comb)])
for cla in range(classes):
    class_info = data[:,cla*bands*regions:(cla+1)*bands*regions]
    for bs in range(bands):
        n = bs*regions
        for i in range(len(comb)):
            index1 = comb[i][0]+n
            index2 = comb[i][1]+n
            part1 = class_info[:, index1]
            part2 = class_info[:, index2]
            coeff[bs, i] = (np.corrcoef(part1, part2))[0, 1]
    bands_info.append(coeff.reshape([1,-1]))
coeff_info = np.vstack((bands_info[0], bands_info[1], bands_info[2],bands_info[3]))

例如这个循环赋值过程,最终得出来的结果是bands_info这个List里面每一个矩阵都是一样的,这是为什么呢?我一开始也在这里纠结了很长时间,思来想去感觉没错的呀。后来想想以前学的C语言知识,才有点明白。原来python里面有浅层copy和深层copy这一说,同是一个矩阵的话占用的是同一个地址,在里面进行重复赋值的话前面的值都会被覆盖掉。不只是当前变量被覆盖掉,就是你之后用到这个变量的也会被覆盖。比如说你a的变量被b覆盖了,那你后面用到a的变量的地方,a的值也会变成b的值。是不是很可怕。
那么应该怎么进行修改呢?

import itertools
import numpy as np
comb = list(itertools.combinations(list(range(regions)), 2))
bands_info = []
for cla in range(classes):
    coeff = np.zeros([bands, len(comb)])
    class_info = data[:,cla*bands*regions:(cla+1)*bands*regions]
    for bs in range(bands):
        n = bs*regions
        for i in range(len(comb)):
            index1 = comb[i][0]+n
            index2 = comb[i][1]+n
            part1 = class_info[:, index1]
            part2 = class_info[:, index2]
            coeff[bs, i] = (np.corrcoef(part1, part2))[0, 1]
    bands_info.append(coeff.reshape([1,-1]))
coeff_info = np.vstack((bands_info[0], bands_info[1], bands_info[2],bands_info[3]))

改成这样就可以了。就是将初始矩阵在循环里在重新设定一遍,意思相当就是给了一次新的地址,再进行复制的话就不会覆盖前面的结果了。

你可能感兴趣的:(python关于矩阵重复赋值会覆盖的问题)