Append overwrites every element with last appended value (Python)
我想准备一个列表列表,其中包含所有可能在蛮力搜索中使用的参数组合。参数组合应如下所示:
[0,0,1]
[0,0.2,0.8]
[0.2、0、0.8]
...
[0.4、0.4、0.2]
...
[1,0,0]
生成这些列表的代码运行良好-在每次迭代中打印weights_temp都会返回正确的结果。但是附加有一些问题。当我打印砝码时,我得到的就是这个(最后的weights_temp值而不是其他元素):
[1.0,0.0,0.0]
[1.0,0.0,0.0]
...
[1.0,0.0,0.0]
...
[1.0,0.0,0.0]
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | step = 0.2 weights_temp = [0, 0, 1] weights = [weights_temp] i = 1 while weights_temp != [1, 0, 0]: # decrease gamma weights_temp[2] = 1 - i * step for j in xrange(0, i + 1): # increase alpha, decrease beta weights_temp[0] = j * step weights_temp[1] = abs(1 - weights_temp[2]) - j * step weights.append(weights_temp) print weights_temp i += 1 |
有人知道如何解决此问题吗?
预先感谢您
继续我的评论,而不是添加引用,而是每次使用列表理解功能添加一个新列表。
1 | weights.append([item for item in weights_temp]) |
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> temp = [1,2,3] >>> holder = [temp] >>> holder [[1, 2, 3]] >>> temp[0] += 1 >>> holder [[2, 2, 3]] >>> holder.append([item for item in temp]) >>> holder [[2, 2, 3], [2, 2, 3]] >>> temp[0] +=1 >>> holder [[3, 2, 3], [2, 2, 3]] |