5.9 比较 Comparisons

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:

不像C语言, 在Python中所有比较运算具有相同的优先级: 比所有算术运算符,移位运算符,和位运算符都要低.并且, 表达式a < b < c 具有和数学上一样的含义:

comparison  ::=  or_expr ( comp_operator or_expr )*
comp_operator  ::=  "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
    | "is" ["not"] | ["not"] "in"
Download entire grammar as text.

Comparisons yield boolean values: True or False.

比较运算生成逻辑值: True 意味着结果为真, False 意味着结果为假,

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

比较可以任意的连接, 例如, x < y <= z 等价于x < y and y <= z,除了y只求值一次(但在这两种情况下, 只要发现x < y 为假, z就不会被计算) .

Formally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy are comparison operators, then a opa b opb c ...y opy z is equivalent to a opa b and b opb c and ... y opy z, except that each expression is evaluated at most once.

形式上, 如果a, b, c, ..., y, z 为表达式, opa, opb, ..., opy 为比较运算符,则a opa b opb c ...y opy z 等价于a opa b and b opb c and ... y opy z, 除了每个表达式最多只求值一次.

Note that a opa b opb c doesn't imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).

注意 a opa b opb c 并没有隐式地规定a 和c 之间的比较运算种类, 所以x < y > z 是完全合法的(虽然可能不太漂亮).

The forms <> and != are equivalent; for consistency with C, != is preferred; where != is mentioned below <> is also accepted. The <> spelling is considered obsolescent.

<>和!=是等价的, 考虑对C语言的连贯性, 推荐使用!=, 以下对!=的讨论对<>也是成立的.<>写法已经考虑废除了.

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.

运算符 <, >, ==, >=, <=, 和 != 比较两个对象的值, 它们不需要具有相同的的类型.如果两个都是数值型的, 它们都转换成通用类型. 否则, 不同类型的对象之间的比较通常是不等的.并且顺序通常是固定的, 但顺序是任意的.

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

(这个不太自然的比较规则用于简化像排序操作和in或not in运算符.以后, 关于不同类型的对象的比较规则很可能会改变.)

Comparison of objects of the same type depends on the type:

相同类型的对象的比较法则依赖于该类型:

The operators in and not in test for set membership. x in s evaluates to true if x is a member of the set s, and false otherwise. x not in s returns the negation of x in s. The set membership test has traditionally been bound to sequences; an object is a member of a set if the set is a sequence and contains an element equal to that object. However, it is possible for an object to support membership tests without being a sequence. In particular, dictionaries support memership testing as a nicer way of spelling key in dict; other mapping types may follow suit.

in运算符和not in 运算符用于测试集合成员. 如果x是集合s的成员, 那么x in s的结果为真, 否则为假. x not in s的结果与上相反. 集合成员测试运算通常用在有序类型对象中; 某对象是集合的一个成员, 即这个有序类型对象包括有与该对象相等的元素.但是也允许不是有序类型的对象支持集合成员测试运算; 特别地, 支持集合成员测试的字典提供了一个不错的方法测试dict中的key; 其它映射类型可能提供类似的机制.

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

对于列表和元组类型, x in y当且仅当y具有合法的索引i, 并且x == y[i]为真.

For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True. Changed in version 2.3: Previously, x was required to be a string of length 1.

对于Unicode和串类型, x in y当且仅当y具有合法的索引i, 并且x == y[i]为真.如果x不是长度为1的字符串或Unicode串, 就会引发 TypeError 异常.

For user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.

对于定义了__contains__()方法 的用户自定义类, x in y为真仅当 y.__contains__(x)返回true.

For user-defined classes which do not define __contains__() and do define __getitem__(), x in y is true if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception. (If any other exception is raised, it is as if in raised that exception).

对于没有定义__contains__()方法但定义有 __getitem__()方法的用户自定义类, x in y当且仅当有一个非负的索引i, 使x == y[i]满足, 并且所有小于该数的索引不能引发IndexError异常(如果引发了任何其它异常, 就好像是该运算引发的一样).

The operator not in is defined to have the inverse true value of in.

运算符not in可计算与运算符in相反的结果.

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

运算符is和is not用于测试对象标识: x is y 为真, 当且仅当x和y是相同的对象, x is not y取其反值.



注脚

... equal.5.3
The implementation computes this efficiently, without constructing lists or sorting.
... defined.5.4
Earlier versions of Python used lexicographic comparison of the sorted (key, value) lists, but this was very expensive for the common case of comparing for equality. An even earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to {}.
...映射(字典)仅当它们存储(键值对)表一样时相等. 5.5
目前实现的计算方法并没有构造中间列表和排序, 因而比较有效率.
... 但还没有定义其它的比较方法.5.6
早些版本的Python对排序后的(键值对)表比较, 但是这样对于一般等价比较的应用来说非常低效.更早的Python版本按仅仅依靠字典的标识比较, 但这时候在你试图用一个空字典和 比较时会得出不期望的结果.