python - 为什么 list(set([2,1,3,6,5,3,6,4])) 会自动对列表进行排序?

标签 python list sorting set

我正在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-printingipython

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/

相关文章:

python - 使用 python 中的第一次出现进行分组排序?

python - 从两个列表创建字典?在取平均值时?

c# - 如何使 DataGridVewLinkColumn 与 DataGridView 的其余部分一起排序

php - 如何让用户插入列表中的任意位置?

python - 在用 Python 写入文件之前如何确保文件存在或可以创建?

python - 从列表项的不同组合创建元素列表

python - Pandas MultiIndex 获取所有具有标签值的行

ios - AnyObject 没有名为 "sort"的成员

python - Ansible:将对象列表传递给 python 脚本

python - 有什么比 django-piston 更好的吗?