numpy的的 '真' 是不一样的 '真' 作为Python的 '真',并为此is
失败:
>>> import numpy as np
>>> a = np.array([True, True, False])
>>> a[:]
array([ True, True, False], dtype=bool)
>>> a[0]
True
>>> a[0]==True
True
>>> a[0] is True
False
>>> type(a[0])
<type 'numpy.bool_'>
>>> type(True)
<type 'bool'>
而且,具体而言,PEP 8说DONT使用 '是' 或 '==' 的布尔:
Don't compare boolean values to True or False using ==:
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
空numpy的阵列做试验falsey只是作为一个空的Python列表或空字典的作用:
>>> [bool(x) for x in [[],{},np.array([])]]
[False, False, False]
与Python中,单falsey元素的numpy的阵列做测试falsey:
>>> [bool(x) for x in [[False],[0],{0:False},np.array([False]), np.array([0])]]
[True, True, True, False, False]
但是你不能使用逻辑与numpy的阵列与一个以上的元素:
>>> bool(np.array([0,0]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
所以' PEP 8 numpy的精神”可能是只测试每个元素的感实性:
>>> np.where(np.array([0,0]))
(array([], dtype=int64),)
>>> np.where(np.array([0,1]))
(array([1]),)
或者使用any
:
>>> np.array([0,0]).any()
False
>>> np.array([0,1]).any()
True
而且要知道,这是不是你所期望的:
>>> bool(np.where(np.array([0,0])))
True
由于np.where
返回一个非空的元组。
你在哪里找到这款PEP8 E712? – mgilson 2013-03-01 18:56:18
这是'pep8'工具的特定诊断输出:https://github.com/jcrocholl/pep8/blob/master/pep8.py#L900。请注意,在这种情况下它是错误的,因为'a是真的'对于数组并不是一件有意义的事情。 – nneonneo 2013-03-01 18:59:04
@mgilson你也可以搜索python'linter'。大部分/某些IDE都有插件来对你的代码进行pep8检查。 – Framester 2013-03-01 19:06:32