为什么在python中[1,2]<[2,1]语句的计算结果为True

2024-03-29 11:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习python编程语言,在此过程中遇到以下语句:

[1,2] < [2,1] evaluating to True

我似乎不明白python是如何在内部进行比较的。你知道吗


Tags: totrue过程语句编程语言evaluating
2条回答

我敢肯定这是一个重复的地方,但当你比较列表,比较正在做lexicographically by each element。Python首先比较1和2,即每个列表的第一个元素。这是真的,所以右列表大于左列表。你知道吗

在每个list中逐项进行比较:

>>> [1, 2] < [2, 1] # 1 < 2: because the first two items differ, comparison ends here
True
>>> [1, 2] == [1, 2] # 1 == 1 and 2 == 2
True
>>> [1, 2][0] < [2, 1][0] # 1 < 2
True
>>> [1, 2][1] > [2, 1][1] # 2 > 1
True

有关Comparing Sequences and Other Types的详细信息:

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal.

相关问题 更多 >