简体   繁体   English

Python中的元组比较

[英]Tuple comparison in Python

According to 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). 例如,cmp([1,2,x],[1,2,y])返回的内容与cmp(x,y)相同。 If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]). 如果相应的元素不存在,则较短的序列将首先排序(例如[1,2] <[1,2,3])。

If I understand correctly 如果我理解正确

(a, b, c) < (d, e, f)

gives True if 如果为真

a < d and b < e and c < f

why 为什么

(1, 2, 3) < (2, 0, 4)

gives True? 给真吗?

how can I do such a comparison? 我该如何进行比较?

Your understanding is flawed. 您的理解是有缺陷的。 It's not and - it's a cascading comparison. 不是and而是-级联比较。

a < d or (a == d and b < e) or (a == d and b == e and c < f)

Another way of understanding this for arbitrary length tuples... 另一种理解任意长度元组的方法...

def tuple_less_than(tuple1, tuple2):
    for item1, item2 in zip(tuple1, tuple2):
        if item1 != item2:
            return item1 < item2
    return len(tuple1) < len(tuple2)

Simply explained, read the values as if they are decimal numbers 简单说明,将值当作十进制数读取

123 < 204

This is oversimplified, but what I mean, it compare elements one by one, and it ends as soon as the elements are not the same. 这被简化了,但是我的意思是,它将元素一一比较,并且一旦元素不相同就结束。

Think of it like comparing 2 strings. 认为它就像比较2个字符串。 The first non-equal comparison of each element determines the comparison result. 每个元素的第一次不相等比较确定比较结果。

(1, 2, 3) < (2, 3)
True

"123" < "23"
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM