仅包含整数的集合是否有序?

Are sets that contain just integers ordered?

我写了这段代码:

s = set(range(10))
print(s)

但每次的结果都是{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}。 集合不是无序的吗? 此代码中的集合始终是有序的但未编入索引。

不,通常不会。

>>> s = {8, 4, 0}
>>> print(s)
{8, 0, 4}

使用 set(range(n)),在当前的 CPython 中,它们被排序是因为每个数字 i 都被放置在散列 table 中的索引 i 处。因为例如 n=20,散列 table 得到 32 行,数字 i 被映射到 hash(i) % 32 = i % 32 = i。因此,当 table 被迭代时,您将对数字进行排序。但这是一个实现细节,所以不要依赖它。

更好的演示,顺便说一句,还表明它不是按“插入顺序”左右排序的,但实际上是排序的:

>>> from random import shuffle
>>> a = list(range(20))
>>> shuffle(a)
>>> a
[14, 15, 5, 17, 3, 18, 16, 7, 8, 19, 2, 10, 12, 6, 1, 9, 11, 4, 0, 13]
>>> set(a)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}

在我上面的 {8, 4, 0} 中,散列 table 有 8 行,因此 8 被映射到 hash(8) % 8 = 8 % 8 = 0 并因此被放入第 0 行。然后 4 被放入第 4 行。然后 0 应该 进入第 0 行,但由于它已经被占用,它必须去别的地方并且显然在数字 84 之间结束,即在第 1、2 或 3 行之一中。

视觉上:

Initial   After     After     After
empty     placing   placing   placing
table:    the 8:    the 4:    the 0:

0:        0: 8      0: 8      0: 8       
1:        1:        1:        1: 0  (or could be at place 2 or 3)       
2:        2:        2:        2:  
3:        3:        3:        3:  
4:        4:        4: 4      4: 4       
5:        5:        5:        5:        
6:        6:        6:        6:        
7:        7:        7:        7: