gpt4 book ai didi

python - Python 中的元组比较

转载 作者:行者123 更新时间:2023-11-28 21:54:45 25 4
gpt4 key购买 nike

根据 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]).

如果我没理解错的话

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

如果

则为真
a < d and b < e and c < f

为什么

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

给出真?

我怎样才能做这样的比较?

最佳答案

你的理解有问题。这不是 - 这是级联比较。

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

另一种理解任意长度元组的方法...

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

关于python - Python 中的元组比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com