python中元组可以比较大小吗,python元组比较

I have been reading the Core Python programming book and the author shows an example like:

(4,5) < (3,5) # Equals false

So I'm wondering, how/why does it equal false? How does python compare these two tuples?

Btw, it's not explained in the book.

解决方案

Tuples are compared position by position:

the first item of first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

See doc:

Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also this:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note that < and > do not mean "smaller then" and "greater then" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as coordinates in a n-dimensional space!

Note 3: referring to question Python 2 tuple comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值