为什么 python 集合按升序“排序”?

myk*_*hoy 5 python set unordered python-3.x python-3.9

让我们运行以下代码:

st = {3, 1, 2}
st
>>> {1, 2, 3}
st.pop()
>>> 1
st.pop()
>>> 2
st.pop()
>>> 3
Run Code Online (Sandbox Code Playgroud)

尽管集合被认为是无序的,但该集合的行为就像按升序排序一样。pop()根据文档,该方法应该返回“任意元素”,也按升序返回元素。这是什么原因呢?

Bha*_*rel 5

该顺序与对象的散列、集合的大小、数字的二进制表示、插入顺序和其他实现参数相关。它是完全任意的,不应依赖:

>>> st = {3, 1, 2,4,9,124124,124124124124,123,12,41,15,}
>>> st
{1, 2, 3, 4, 9, 41, 12, 15, 124124, 123, 124124124124}
>>> st.pop()
1
>>> st.pop()
2
>>> st.pop()
3
>>> st.pop()
4
>>> st.pop()
9
>>> st.pop()
41
>>> st.pop()
12
>>> {1, 41, 12}
{1, 12, 41}
>>> {1, 9, 41, 12}
{1, 12, 9, 41}  # Looks like 9 wants to go after 12.
>>> hash(9)
9
>>> hash(12)
12
>>> hash(41)
41
>>> {1, 2, 3, 4, 9, 41, 12}
{1, 2, 3, 4, 9, 12, 41}  # 12 before 41
>>> {1, 2, 3, 4, 9, 41, 12, 15}  # add 15 at the end
{1, 2, 3, 4, 9, 41, 12, 15}  # 12 after 41
Run Code Online (Sandbox Code Playgroud)