它是保证假" 0"和True" 1"? [英] Is it guaranteed that False "is 0" and True "is 1"?

查看:220
本文介绍了它是保证假" 0"和True" 1"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarante\">Is假== 0和True == 1在Python实现细节抑或是由语言保证?


今天我注意到,使用python 2.6以下作品(CPython的)...

 &GT;&GT;&GT; A = [100,200]
&GT;&GT;&GT;一个[真]
200
&GT;&GT;&GT;一个[虚假]
100

时这个移植到其他Python实现(例如是 / 保证从int继承?是保证计算结果为1,而不是其他一些非零数字?)是否有任何情况下,这将是有益的?现在看来似乎可以作为一个三元运算符的另一种形式,但我不知道有多少是获得了有...


解决方案

部分语言规范的,所以任何的Python实现的的实施布尔等同于整数。


  

布尔


  
  

    

这些重新present真值假和真。两个对象重新presenting值假和真是唯一布尔对象。布尔类型是普通整数的子类型和布尔值分别表现得像值0和1,在几乎所有环境中,唯一的例外是,当转换为字符串,字符串返回,分别为。


  

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

I noticed today that the following works using python 2.6 (Cpython)...

>>> a=[100,200]
>>> a[True]
200
>>> a[False]
100

Is this portable to other python implementations (e.g. is True/False guaranteed to inherit from int? Is True guaranteed to evaluate to 1 instead of some other non-zero number?) Is there any situation where this would be useful? It seems like it could be used as another form of a ternary operator, but I don't know how much is gained there...

解决方案

It is part of the language specification, so any Python implementation should implement the booleans as equivalent to the integers.

Booleans

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

这篇关于它是保证假&QUOT; 0&QUOT;和True&QUOT; 1&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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