当你比较不同大小的列表时会发生什么?

What happens when you compare lists of different sizes?

在 Python 中,我有两个不同大小的列表:

x = [[0,5,10],[0,10,5]]
y = [100,500,900]

当我 运行:

时,每一步发生的比较是什么
print x>y

例如它如何比较第一个元素:[0,5,10] 与 100?

那些比较是行不通的。 listint 无法比较。所以不行

在 Python 3 中,您无法比较这两个列表,因为它们的元素不是可比较的类型。

在 Python 2 中,列表总是大于整数,句号,因此无论 x 中有什么元素,您的 x 总是大于您的 y的子列表。

真正的问题是如何比较 [0,5,10]100,即列表与整数。

答案取决于 Python 版本。在Python3.x中,这两种类型是不能比较的。在 Python 2.x 中,列表总是大于整数,因为类型名称 list 大于 int.

在您的示例中,print 中的语句

print x>y

表明您正在使用 Python 2.x,所以答案是 x > y 将是 True

只是为了扩展其他答案,关于这方面的文档非常好。来自 the 2.7 documentation:

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.

来自the 3.5 documentation

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. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.

本质上 x == y 在对象上使用神奇的 __eq__ 方法来比较它们。不同的对象会有不同的行为,您甚至可以定义自己的自定义相等性,但通常比较不同类型的对象总是会评估为 FalsePython2 and Python3 文档)。

因此在您的示例中,[0,5,10] == 100 的计算结果为 False,不是因为它检查列表中的元素是否等于 100,而是因为这两种类型不兼容。