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). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [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.
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. The first non-equal comparison of each element determines the comparison result.
(1, 2, 3) < (2, 3)
True
"123" < "23"
True
链接地址: http://www.djcxy.com/p/53590.html
上一篇: 作为**解包映射的python类
下一篇: Python中的元组比较