set add()方法对集合进行排序?

kninwzqo  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(376)

使用pythonsetadd方法,我注意到该方法根据值和集合的内容对内容进行排序。

根据docstring,可以找到以下方法说明:

为什么会这样?有没有办法避免这种情况发生?
我正在使用python 3.6。

kadbb459

kadbb4591#

即使你见过这种“有序”的行为一次,也并不意味着它总是如此。简单的例子:

w = set()
for i in range(100):
    w.add(i)
    w.add(str(i))

print(w)

输出:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
 17, 18, 19, 20, '20', 21, 22, 23, 24, 25, 26, 27, 28, 29, 
 30, 32, 33, 34, 35, 36, 37, '9', 38, 31, 39, 40, 41, 42, 
 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, '52', 53, 54, 55, 
 56, 57, 58, 59, 60, 61, '61', 62, 63, 64, '26', 65, 66, 
 67, '58', '36', 68, '6', '68', 69, '18', 71, 72, '4', 74, 
 75, 76, 77, '77', 79, 80, 81, 82, '12', '46', 85, 86, 87, 
 '33', 89, 90, 91, 92, 93, 94, 95, '23', '24', 98, 99, '49', 
 '92', '30', '44', '7', '21', '93', '86', '2', '67', '57', 
 '13', '79', '80', '96', '38', '32', '15', '45', '64', '83', 
 '65', '54', '88', '48', '75', '99', '71', '5', '0', '28', 
 '87', '43', '94', '90', '72', '42', '37', '59', '35', '8', 
 '17', '10', 70, 73, '98', '22', '19', '11', '27', '34', '14', 
 '56', '55', '69', '66', 78, '3', '1', '53', '84', '16', '25', 
 '76', 83, '82', '29', 84, '95', '31', '70', 88, '97', '40', 
 '47', '51', '85', '91', '60', '81', '89', 96, '78', '62', 
 '73', '74', 97, '41', '39', '50', '63'}

如果它真的分类了什么,它也应该
交替输入int或字符串值(插入顺序)
先显示已排序的所有整数,然后显示已排序的所有字符串
或者其他某种“可检测”的模式。
使用非常小的样本集(范围(10))或非常有限的值(所有整数)可以/可能会根据集合的内部扣合策略导致“有序”输出。

4nkexdtk

4nkexdtk2#

请不要指望这种行为:

>>> x = set()
>>> for i in range(10):
...     x.add(i)
... 
>>> x
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> for i in range(1000, 1020):
...     x.add(i)
... 
>>> x
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019}
>>> x.remove(2)
>>> x
{0, 1, 3, 4, 5, 6, 7, 8, 9, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019}
>>> x.add(2)
>>> x
{0, 1, 3, 4, 5, 6, 7, 8, 9, 2, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019}

相关问题