在 python 中,内置集合比较元素时明确假设它们是自反的:
In enforcing reflexivity of elements, the comparison of collections assumes that for a collection element x, x == x is always true. Based on that assumption, element identity is compared first, and element comparison is performed only for distinct elements.
逻辑上,这意味着对于任何列表 L
,L == L
必须为 True
。鉴于此,为什么实现不检查身份以缩短评估?
In [1]: x = list(range(10000000))
In [2]: y = list(range(int(len(x)) // 10))
In [3]: z = [1]
# evaluation time likes O(N)
In [4]: %timeit x == x
10 loops, best of 3: 21.8 ms per loop
In [5]: %timeit y == y
100 loops, best of 3: 2.2 ms per loop
In [6]: %timeit z == z
10000000 loops, best of 3: 36.4 ns per loop
显然,子类可以选择进行身份检查,而且身份检查显然会为每次此类比较增加非常小的开销。
是否有历史决定明确不在内置序列中进行此类检查以避免此费用?
最佳答案
虽然我不知道开发人员的想法,但我的猜测是他们可能觉得比较 L == L
的发生频率不足以保证进行特殊检查,而且,用户总是可以使用 (L is L) or (L==L)
来构建一个
如果他认为有利,则短路检查自己。
In [128]: %timeit (x is x) or (x == x)
10000000 loops, best of 3: 36.1 ns per loop
In [129]: %timeit (y is y) or (y == y)
10000000 loops, best of 3: 34.8 ns per loop
关于python - 集合比较是自反的,但不会短路。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779970/