排序 python 元组包含不可比较的元素

Sorting python tuples contain non-comparable elements

尝试比较字典时,python 引发类型错误:

{"a" : "b"} < {"a" : "b"} # TypeError

尝试比较元组时,python 按元素进行比较:

(1, 2) > (1, 1) # True

因此,如果字典前面的元素相等,我预计比较包含字典的元组会导致 TypeError,因为它将被迫比较字典,这会引发 TypeError。事实并非如此:

(3, {"a" : "b"}) < (3, {"a" : "b"}) # False, no TypeError

我已经通读了我能找到的关于 Python 排序的文档,但没有看到任何记录此行为的内容。我可以相信这种行为在未来的版本中保持不变吗?

这在docs中有解释:

Lexicographical comparison between built-in collections works as follows:

For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).

Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

所以元组比较要做的第一件事就是找到不相等的元素,因为你的元组中没有不相等的元素所以结果是 False,并且不需要调用代码<.

通过查看 comparison of tuples:

的实现进一步证实了这一点
for (i = 0; i < vlen && i < wlen; i++) {
    int k = PyObject_RichCompareBool(vt->ob_item[i],
                                     wt->ob_item[i], Py_EQ);
    if (k < 0)
        return NULL;
    if (!k)
        break;
}

if (i >= vlen || i >= wlen) {
    /* No more items to compare -- compare sizes */
    Py_RETURN_RICHCOMPARE(vlen, wlen, op);
}

上面代码中的 for 循环试图找到第一个不相等的元素,如果没有找到,则将比较委托给元组的大小。