2014-01-08 63 views
5

はPythonで次のような問題を考えてみましょう:なぜタプルはPythonのリストよりも大きいですか?

>>>() < [] 

この文歩留まりFalse

>>>() > [] 

がTRUEに評価します。私の知る限りでは、[]Falseになりますが、空のタプルは何ですか?

我々は

>>> 1233 < (1,2) 

を入力した場合我々は戻り値として、Trueを取得します。しかし、なぜ ?

おかげ

+0

python2では「True」のみです。 – iMom0

+0

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

+0

@BartoszKPそれはpython2なのですか? http:// ideone。com/sMggNX – iMom0

答えて

3

真である

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

戻るのpython 2:ドキュメントは、これはは任意ですが、一貫順序であることを強調します。

cPython 2では、不等タイプがその型名によって比較されます。したがって、tupleは辞書順に "listより大きい"です。 Built-in Types - Comparisonsに記載されているよう

0

これは実装に依存することができ、私は、このためには直接の理由はないと思います。 Python 3.Xは、2つの異なるタイプ間の比較を一切禁止します。 docsから

2

これは、CPythonの(2.xの)実装の詳細である:

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はこのメソッドを使用しません。

あなたは3.0より低いpythonバージョンを使用しています。 Pythonのバージョン3.xで
は、例外があるでしょう:
は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.

関連する問題