为什么元组比python中的列表大? [英] Why is tuple larger than a list in python?

查看:36
本文介绍了为什么元组比python中的列表大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑 Python 中的以下问题:

<预><代码>>>>() <[]

这个语句产生 False

<预><代码>>>>() >[]

产生真.据我所知,[] 等于 False,但什么是空元组?

如果我们输入

<预><代码>>>>第 1233 章(1,2)

我们得到一个 True,作为返回值.但为什么 ?

谢谢

解决方案

来自 文档:

<块引用>

运算符 <、>、==、>=、<= 和 != 比较两个对象.对象不必具有相同的类型.如果两者都是数字,它们被转换为通用类型.否则,不同的对象类型总是比较不相等,并且顺序一致但随意.您可以控制对象的比较行为通过定义 __cmp__ 方法或丰富的比较来获取非内置类型__gt__ 等方法,在 3.4 节中描述.​​

(这个不寻常的比较定义被用来简化操作的定义,如排序和 in 和 not in 运算符.未来不同类型对象的比较规则为可能会改变.)

这是真的.在 python 3 中,这是一个 TypeError.

() >[]---------------------------------------------------------------------------TypeError Traceback(最近一次调用最后一次)<ipython-input-3-d2326cfc55a3>在 <module>()---->1 () >[]类型错误:无法排序的类型:元组()>列表()

回到 python 2:文档强调这是一个任意但一致的排序.

cPython 2 中,不相等的类型通过它们的类型名称进行比较.所以 tuple 在字典上大于"list.

Consider following problem in Python:

>>> () < []

this statement yield False and

>>> () > [] 

yields True. So far as I know, [] equals False, but what is an empty tuple ?

If we type

>>> 1233 < (1,2)

We get a True, as return value. But why ?

Thanks

解决方案

From the docs:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a __cmp__ method or rich comparison methods like __gt__, described in section 3.4.

(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)

Which is true. In python 3 this is a TypeError.

() > []
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-d2326cfc55a3> in <module>()
----> 1 () > []

TypeError: unorderable types: tuple() > list()

Back to python 2: The docs stress that this is an arbitrary, but consistent ordering.

In cPython 2, unequal types are compared by their type name. So tuple is "greater than" list, lexicographically.

这篇关于为什么元组比python中的列表大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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