python建立一个空数组,numpy的追加到一个空数组

1st case :

>>> import numpy as np

>>> x=np.array(0)

>>> x=np.append(x,1)

>>> x

array([0, 1])

x contains 2 elements. Why is that ?!

2nd case :

>>> x=np.array([])

>>> x=np.append(x,1)

>>> x

array([ 1.])

x contains 1 element, as expected.

What's the difference between np.array(0) and np.array([]) ?

解决方案

In your first case, you are creating an array called x that will containing one value, which is 0.

In your second case you are creating an empty array called x that will contain no values, but is still an array.

FIRST CASE

So when you append x = np.append(x,1), the value 1 get's appended to your array (which already contains 0) i.e. it now contains 0 and 1

SECOND CASE

Since you have no values in the empty array, when you append x=np.append(x,1) the value 1 get's appended and the length of x becomes 1 (i.e. it now contains only 1)

P.S. I believe you might have thought that calling x = np.array(0) with the 0 would make it an empty array, it doesn't!! In Python, 0 is still taken to be a number and is appended to the array.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值