Python for loop in numpy

2024-03-28 10:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我碰巧碰到了这个词:

np.array([[0. for _ in range(20)] for _ in range(50)])

对于一个20×50的矩阵,它给出了0.0。在

但是,我不喜欢这种语法。我想知道有没有其他的办法?我希望0是0.0(浮点数)。在

谢谢


Tags: infornp语法range矩阵array浮点数
2条回答
np.zeros((20, 50), dtype=np.float32)  # or any other type; default: np.float64

Link to the Docs

备注:没有经验丰富的numpy用户会在您的示例中使用这种方法!在

>>> a=np.zeros([5,8])
>>> a
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
>>> type(a[1][1])
<type 'numpy.float64'>
>>>

从代码中可以看到,默认格式是float64。在

相关问题 更多 >