gpt4 book ai didi

python - 我怎样才能获得List.__gt__()函数的源实现

转载 作者:行者123 更新时间:2023-12-01 07:08:00 25 4
gpt4 key购买 nike

我是一个新的Python程序员,我的代码如下,我很困惑为什么我得到true的结果。好像调用了List的__gt__内置函数。我不知道在哪里可以得到List.gt()内部(内置)函数的源代码。

L1 = ['abc', ['123', '456']]
L2 = ['1', '2', '3']
print(L1 > L2)

如果有人给出答案,我会非常感激。

最佳答案

该行为在文档中得到了很好的说明,因此您实际上不需要阅读源代码来理解它(但请参阅本答案末尾的我的评论):

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.

https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types

值得注意的是,Python 3 不再允许比较任意对象对(Python 2 中就是这种情况)。这可以通过稍微修改您的示例来说明:

>>> L1 = ['1', ['123', '456']]
>>> L2 = ['1', '2', '3']
>>> print(L1 > L2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: list() > str()

但是,如果读完所有这些,您仍然希望阅读 CPython 源代码,可以在 https://github.com/python/cpython 获取

特别地,列表比较代码可以在https://github.com/python/cpython/blob/master/Objects/listobject.c#L2634找到

关于python - 我怎样才能获得List.__gt__()函数的源实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58351944/

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