2014-01-08 4 views
5

Рассмотрим следующую задачу в Python:Почему кортеж больше, чем список в python?

>>>() < [] 

это утверждение выход False и

>>>() > [] 

дает True. Насколько я знаю, [] равно False, но что такое пустой кортеж?

Если мы наберем

>>> 1233 < (1,2) 

Получает True, в качестве возвращаемого значения. Но почему ?

Благодаря

+0

Только 'True' в python2. – iMom0

+0

@ user995394 http://ideone.com/10x5fN – BartoszKP

+0

@BartoszKP Это python2, так? Http: // ideone.com/sMggNX – iMom0

ответ

3

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

Что является правдой. В python 3 это TypeError.

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

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

Вернуться к питону 2: Документы подчеркнуть, что это произвольно, но в соответствии упорядочения.

В cPython 2, неравные типы сравниваются по типу. Таким образом, tuple «больше, чем» list, лексикографически.

0

Это может быть зависит от конкретной реализации, и я думаю, что нет прямых оснований для этого. Python 3.X запрещает сравнение между двумя разными типами.

2

Это деталь реализации CPython (2.x), как описано в Built-in Types - Comparisons:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

Таким образом, любой кортеж сравнивает больше любого списка, потому что 'tuple' > 'list'.

Это больше не выполняется в CPython 3 и никогда не сохранялось для других реализаций Python 2.x.

0

Это потому, что python 2.x использует метод __cmp__().
Python 3.x не будет использовать этот метод.

Вы используете версию python ниже 3.0.
С питона версии 3.х, будет исключение:
TypeError: unorderalbe типы ...

1

Ссылаясь на documentation:

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

Так что, как представляется, зависит от реализации. Например, в CPython:

Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

Смежные вопросы