2013-03-01 34 views
6

PEP8 E712要求“与True应比较if cond is True:if cond:”。与布尔numpy阵列比较VS PEP8 E712

但是,如果我按照这PEP8我得到不同/错误的结果。为什么?

In [1]: from pylab import * 

In [2]: a = array([True, True, False]) 

In [3]: where(a == True) 
Out[3]: (array([0, 1]),) 
# correct results with PEP violation 

In [4]: where(a is True) 
Out[4]: (array([], dtype=int64),) 
# wrong results without PEP violation 

In [5]: where(a) 
Out[5]: (array([0, 1]),) 
# correct results without PEP violation, but not as clear as the first two imho. "Where what?" 
+0

你在哪里找到这款PEP8 E712? – mgilson 2013-03-01 18:56:18

+2

这是'pep8'工具的特定诊断输出:https://github.com/jcrocholl/pep8/blob/master/pep8.py#L900。请注意,在这种情况下它是错误的,因为'a是真的'对于数组并不是一件有意义的事情。 – nneonneo 2013-03-01 18:59:04

+0

@mgilson你也可以搜索python'linter'。大部分/某些IDE都有插件来对你的代码进行pep8检查。 – Framester 2013-03-01 19:06:32

回答

2

该建议仅适用于if声明测试值的“真实性”。 numpy是不同的野兽。

>>> a = np.array([True, False]) 
>>> a == True 
array([ True, False], dtype=bool) 
>>> a is True 
False 

注意a is True总是False因为a是一个数组,而不是一个布尔值,和is执行一个简单的参考相等测试(所以只有True is True; None is not True例如)。

6

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返回一个非空的元组。