我们为什么要检查一个数组是否为empty?数组不会像列表那样增长或收缩。从一个“空”数组开始,到np.append 增长是一个常见的新手错误。
在if alist: 中使用列表取决于其布尔值:
In [102]: bool([])
Out[102]: False
In [103]: bool([1])
Out[103]: True
但尝试对数组执行相同操作会产生(在 1.18 版中):
In [104]: bool(np.array([]))
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value
of an empty array is ambiguous. Returning False, but in
future this will result in an error. Use `array.size > 0` to
check that an array is not empty.
#!/usr/bin/python3
Out[104]: False
In [105]: bool(np.array([1]))
Out[105]: True
而bool(np.array([1,2]) 会产生臭名昭著的歧义错误。
编辑
接受的答案建议size:
In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0
但我(和大多数其他人)检查shape 比size 更多:
In [13]: x.shape
Out[13]: (0,)
对它有利的另一件事是它“映射”到empty 列表:
In [14]: x.tolist()
Out[14]: []
但还有其他具有 0 size 的数组,在最后一种意义上不是“空”的:
In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True
np.array([[],[]]) 也是大小 0,但形状 (2,0) 和 len 2。
虽然empty 列表的概念定义明确,但empty array 定义不明确。一个空列表等于另一个。对于size 0 数组则不能这样说。
答案真的取决于