核心对象类型复习和总结——比较、相等和为真——Python 2.X 和 3.X 混合类型比较和排序

未匹配的标注

根据前面章节列表中的最后一点,3.X中对于非数字混合类型比较的改变适用于大小测试,而非相等测试,但它也适用于代理排序(在内部进行大小测试)。在2.X,这些操作都可以,虽然混合类型通过任意顺序来比较:

c:\code> c:\python27\python
>>> 11 == '11' # Equality does not convert non-numbers
False
>>> 11 >= '11' # 2.X compares by type name string: int, str
False
>>> ['11', '22'].sort() # Ditto for sorts
>>> [11, '11'].sort()

但3.X不允许混合类型大小测试,除了数字类型和手动转换的类型:

c:\code> c:\python33\python
>>> 11 == '11' # 3.X: equality works but magnitude does not
False
>>> 11 >= '11'
TypeError: unorderable types: int() > str()
>>> ['11', '22'].sort() # Ditto for sorts
>>> [11, '11'].sort()
TypeError: unorderable types: str() < int()
>>> 11 > 9.123 # Mixed numbers convert to highest type
True
>>> str(11) >= '11', 11 >= int('11') # Manual conversions force the issue
(True, True)

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 查看所有版本


暂无话题~