python关于矩阵重复赋值覆盖问题的解决方法
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
赞 (0)