【问题标题】:Creating empty 2 dimensional arrays in Python? [duplicate]在 Python 中创建空的二维数组? [复制]
【发布时间】: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


    【解决方案1】:

    因此,我的问题是为什么以及如何更改它?

    使用列表推导替换weights = [[0]*3]*3,如下所示:

    weights = [[0]*3 for _ in range(3)]
    

    【讨论】:

    • 是的,谢谢。但是为什么我不能访问每个条目?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2020-08-02
    • 2020-04-21
    相关资源
    最近更新 更多