gpt4 book ai didi

python - 与 bool numpy 数组 VS PEP8 E712 的比较

转载 作者:太空狗 更新时间:2023-10-29 21:29:26 25 4
gpt4 key购买 nike

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

最佳答案

Numpy 的“True”与 Python 的“True”不同,因此 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对 bool 值使用“is”或“==”:

Don't compare boolean values to True or False using ==:

Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:

一个空的 numpy 数组会像一个空的 Python 列表或空的字典一样测试假值:

>>> [bool(x) for x in [[],{},np.array([])]]
[False, False, False]

与 Python 不同,单个错误元素的 numpy 数组会测试错误:

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

关于python - 与 bool numpy 数组 VS PEP8 E712 的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15164775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com