与布尔numpy数组VS PEP8 E712的比较 [英] Comparison with boolean numpy arrays VS PEP8 E712

查看:108
本文介绍了与布尔numpy数组VS PEP8 E712的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP8 E712要求与True的比较应为if cond is True:if cond:".

但是,如果我遵循此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?"

解决方案

该建议仅适用于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). /p>

PEP8 E712 requires that "comparison to True should be if cond is True: or if cond:".

But if I follow this PEP8 I get different/wrong results. Why?

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?"

解决方案

That advice only applies to if statements testing for the "truthiness" of a value. numpy is a different beast.

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

Note that a is True is always False because a is an array, not a boolean, and is does a simple reference equality test (so only True is True; None is not True for example).

这篇关于与布尔numpy数组VS PEP8 E712的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆