gpt4 book ai didi

python - 是否有任何 Python2 的实现可以传递排序?

转载 作者:太空狗 更新时间:2023-10-29 21:02:51 26 4
gpt4 key购买 nike

是否有任何现有的 Python2 实现,其顺序为 transitive ?也就是说,如果不创建用户定义的类型就不可能看到这种行为:

>>> x < y < z < x
True

由于这个反例,CPython 是不可传递的

x = 'b'
y = ()
z = u'ab'

但是,在 CPython 中这个顺序是 documented作为一个实现细节。

最佳答案

除了 Skulpt 之外,每个主流 Python 实现都以某种方式失败,但可以说它是一个不完整的实现。

CPython(和变体)、PyPy 和 Jython:

>>> 'b' < () < u'ab' < 'b'
True

IronPython:

IronPython 在内部比较 .NET Object.GetHashCode()不同对象的哈希值,因此您可以通过滥用 int 的特殊处理来破坏它和 float比较和 float('+inf') 的内部哈希表示的事实小于 [] 的哈希值(我不确定这有多稳定,所以它可能不适用于所有 IronPython 安装):

>>> 2**200 < float('+inf') < [] < 2**200
True

CLPython

>>> {1: 3} < {1: 4} < {1: 3}
1
>>> {1: 3} < {1: 3}
0

雕刻

如果算上Skulpt作为 Python 2 的完整实现(它不能比较字典和其他一些不方便的类型,并且没有 unicode 类型),它实际上通过复制 CPython 的比较规则并方便地省略 unicode 来工作。输入:

# 1. None is less than anything
# 2. Sequence types are greater than numeric types
# 3. [d]ict < [l]ist < [s]tring < [t]uple

>>> None < 0 < {} < [] < '' < ()
True

对于 CPython 2,你实际上会有 [t]uple < [u]nicode , 但因为 unicodestr比较被作为特例处理,你失去了传递性。尽管 Python 2 不太可能获得修复此“错误”的补丁,但我认为您可以通过显式更改顺序来确保传递性:

[d]ict < [l]ist < [s]tring < [t]uple < [u]nicode

收件人:

[u]nicode < [d]ict < [l]ist < [s]tring < [t]uple

这样,str 的特例至 unicode比较不会破坏任何东西。

关于python - 是否有任何 Python2 的实现可以传递排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40181259/

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