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

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

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.

这很有意义,因为尽管1和True都与if语句的条件相同,但它们实际上并不是一回事。

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

再次编辑:1 == True的更有趣的后果:

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

8 个解决方案

#1


33

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

因为Python中的布尔值是整数的子类型。从文档:

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).

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

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

更多相关文章

  1. 'str'对象不能解释为groupby上的整数
  2. 用python将二进制整数或字符串写入文件
  3. 我的电脑认为有符号整数比-1小?
  4. linux shell 里面,真值为0,假值为非0
  5. 请教用sql loader导入数据,最后一位是整数的问题
  6. js实现把整数秒转化为"hh:mm:ss"的时间格式.
  7. 给定一个整数数组,找出两个下标,要求后面下标所指的数减去前面下标
  8. 生成真值组合【Java实现】

随机推荐

  1. Android应用程序四大组件
  2. Android的布局控件----LinearLayout(线性
  3. Android 在 xml中定义图片
  4. android设置一个通用的控件,比如返回按钮
  5. Android:ImageView如何显示网络图片
  6. 实现ListView的item逐个飞入效果——Layo
  7. button imageButton 背景透明
  8. android:imeOptions
  9. Android短信数据库简析
  10. linux eclipse中运行android AVD 错误