为什么在 Python 中 1 == True 但 2 != True? [英] Why does 1 == True but 2 != True in Python?

查看:86
本文介绍了为什么在 Python 中 1 == True 但 2 != True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
是假的Python 中的 == 0 和 True == 1 是实现细节还是由语言保证?

来自我的交互式控制台的简短记录:

Python 2.7.2(默认,2011 年 6 月 29 日,11:10:00)[GCC 4.6.1] 在 linux2 上输入帮助"、版权"、信用"或许可"以获取更多信息.>>>真的真的>>>0 == 真错误的>>>1 == 真真的>>>2 == 真错误的

这到底是为什么?

为了对比,考虑 is 运算符.

<预><代码>>>>0 是假的错误的>>>1 是真的错误的>>>0 是 0真的>>>真的是真的真的

这很有意义,因为尽管 1True 都与 if 语句的条件含义相同,但它们确实不是一回事.

再次1 == True 更有趣的结果:

<预><代码>>>>d = {}>>>d[真] = "你好">>>d[1]你好"

解决方案

因为 Python 中的 Boolean 是整数的子类型.来自文档:

<块引用>

布尔值是两个常量对象 False 和 True.它们用于表示真值(尽管其他值也可以被视为假或真).在数字上下文中(例如,当用作算术运算符的参数时),它们的行为分别类似于整数 0 和 1.内置函数 bool() 可用于将任何值转换为布尔值,前提是该值可以解释为真值(请参阅上面的真值测试部分).

http://docs.python.org/library/stdtypes.html#boolean-values

Possible Duplicate:
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

A brief transcript from my interactive console:

Python 2.7.2 (default, Jun 29 2011, 11:10:00) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True
True
>>> 0 == True
False
>>> 1 == True
True
>>> 2 == True
False

Why on earth is this the case?

Edit: For the sake of contrast, consider the is operator.

>>> 0 is False
False
>>> 1 is True
False
>>> 0 is 0
True
>>> True is True
True

That makes a lot of sense because though 1 and True both mean the same thing as the condition of an if statement, they really aren't the same thing.

Edit again: More fun consequences of 1 == True:

>>> d = {}
>>> d[True] = "hello"
>>> d[1]
"hello"

解决方案

Because Boolean in Python is a subtype of integers. From the documentation:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

http://docs.python.org/library/stdtypes.html#boolean-values

这篇关于为什么在 Python 中 1 == True 但 2 != True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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