我正在Python中尝试set
,虽然我知道它是unsorted, based on hashes ,我觉得奇怪的是它会自动对这些数字进行排序,无论是在 Python 2 还是在 3 中:
>>> list(set([2,1,3,6,5,3,6,4]))
[1, 2, 3, 4, 5, 6]
>>> list(set([2,1,3,6,5,3,6,4,0,7]))
[0, 1, 2, 3, 4, 5, 6, 7]
我用谷歌搜索了一段时间,但没有找到这两个函数组合的行为的答案。
最佳答案
事实并非如此,这是一个例子
In [2]: list(set([1,9,5,10]))
Out[2]: [1, 10, 5, 9]
此外,来自文档:https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset
A set object is an unordered collection of distinct hashable objects.
有时您看到排序输出的原因取决于 hash
的方式是计算的,有时是根据正在使用的 REPL 进行计算的,并且此行为在 answer 中得到了很好的描述。
ipython
的示例,当我们启用 doctest_mode 时,集合的打印方式会发生变化。 ,这会禁用 pretty-printing
的ipython
In [1]: set([1,6,8,4])
Out[1]: {1, 4, 6, 8}
In [2]: %doctest_mode
Exception reporting mode: Plain
Doctest mode is: ON
>>> set([1,6,8,4])
{8, 1, 4, 6}
关于python - 为什么 list(set([2,1,3,6,5,3,6,4])) 会自动对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56185552/