python vs numpy中的布尔值和类型检查 [英] boolean and type checking in python vs numpy

查看:246
本文介绍了python vs numpy中的布尔值和类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在python if子句中遇到了意外的结果:

I ran into unexpected results in a python if clause today:

import numpy
if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5):
    print 'close enough'  # works as expected (prints message)

if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5) is True:
    print 'close enough'  # does NOT work as expected (prints nothing)

经过一番摸索(例如,此问题,尤其是

After some poking around (i.e., this question, and in particular this answer), I understand the cause: the type returned by numpy.allclose() is numpy.bool_ rather than plain old bool, and apparently if foo = numpy.bool_(1), then if foo will evaluate to True while if foo is True will evaluate to False. This appears to be the work of the is operator.

我的问题是:为什么numpy具有自己的布尔类型,鉴于这种情况,最佳实践是什么?在上面的示例中,我可以写if foo:来获得预期的行为,但是我喜欢更严格的if foo is True:,因为它从返回True中排除了2[2]之类的东西,有时还不包括显式类型检查是可取的.

My questions are: why does numpy have its own boolean type, and what is best practice in light of this situation? I can get away with writing if foo: to get expected behavior in the example above, but I like the more stringent if foo is True: because it excludes things like 2 and [2] from returning True, and sometimes the explicit type check is desirable.

推荐答案

为什么numpy有自己的布尔类型

why does numpy have its own boolean type

空间和速度. Numpy将事物存储在紧凑的数组中;如果它可以将布尔值放入单个字节中,则将尝试.使用Python对象很难做到这一点,因为您必须存储引用,这会大大降低计算速度.

Space and speed. Numpy stores things in compact arrays; if it can fit a boolean into a single byte it'll try. You can't easily do this with Python objects, as you have to store references which slows calculations down significantly.

在上面的示例中,我可以放弃编写if foo:来获得预期的行为,但是如果foo为True,我喜欢更严格的方法:因为它排除了2和[2]之类的返回True的功能,有时还不包括显式的类型检查是可取的.

I can get away with writing if foo: to get expected behavior in the example above, but I like the more stringent if foo is True: because it excludes things like 2 and [2] from returning True, and sometimes the explicit type check is desirable.

好吧,不要那样做.

这篇关于python vs numpy中的布尔值和类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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