【发布时间】:2021-02-15 11:17:19
【问题描述】:
我正在尝试在 Python 中创建一个空数组。稍后我想给每个空间写一个唯一的数字。
这是我的代码:
import numpy as np
# First Method
weights = [[0]*3]*3
for i in range(len(weights)):
for j in range(len(weights[0])):
weights[i][j] = float(np.random.rand(1))
print (weights)
# Second Method
weights2 = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(weights2)):
for j in range(len(weights2[0])):
weights2[i][j] = float(np.random.rand(1))
print (weights2)
这是输出:
first: [[0.08888843613599318, 0.6057538355394358, 0.9116018147777744], [0.08888843613599318, 0.6057538355394358, 0.9116018147777744], [0.08888843613599318, 0.6057538355394358, 0.9116018147777744]]
second: [[0.6196830850283566, 0.4767956303875597, 0.11175364311603775], [0.6237674876857202, 0.5810440548445903, 0.10874630848820122], [0.6923495438022649, 0.38815857621698835, 0.22380090955172283]]
如您所见,第一个数组包含三组相同的三个数字,而第二个数组则没有。
因此,我的问题是为什么以及如何更改它?
【问题讨论】:
标签: python arrays python-3.x