集合是否像python3.6中的字典一样排序 [英] Are sets ordered like dicts in python3.6

查看:140
本文介绍了集合是否像python3.6中的字典一样排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Python 3.6中 dict 实现的更改,因此默认情况下将其排序。 set 的订单现在还保留吗?

Due to changes in dict implementation in Python 3.6 it is now ordered by default. Do sets preserve order as well now?

我找不到关于它的任何信息,但由于这两个原因数据结构在幕后的工作方式中非常相似。

I could not find any information about it but as both of those data structures are very similar in the way they work under the hood I thought it might be the case.

我知道 dict没有前景在所有情况下都可以订购,但大多数情况下都是这样。如Python文档中所述:

I know there is no promise for dicts to be ordered in all cases but they are most of the time. As stated in Python docs:


此新实现的顺序保留方面被视为实现细节,因此不应依赖

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon


推荐答案

不, set 仍然

您可以通过显示来验证这一点,该集应具有定义明确的哈希顺序 1 以确保我们不会偶然得到看起来有序但实际上不是的集合

You can verify this just by displaying a set that should have a "well-defined hash order"1 to make sure we don't accidentally get a set that looks ordered but actually isn't:

>>> a_set = {3,2,1}
>>> a_set
{1, 2, 3}
>>> list(a_set)
[1, 2, 3]

如果订购了根据示例,预计 {3,2,1} [3,2,1]

If it were ordered you would expect {3, 2, 1} and [3, 2, 1] as result of the examples.

实际上已订购了 dict 个命令(相同的示例稍作修改):

While dicts are actually ordered (same example just a bit modified):

>>> a_dict = {3: 3, 2: 2, 1:1}
>>> a_dict
{3: 3, 2: 2, 1: 1}
>>> list(a_dict)
[3, 2, 1]






1 定义良好的哈希顺序:


1 "well-defined hash order":

对于满足 0≤的整数整数< sys.hash_info.modulus 哈希只是数字本身。这意味着如果该集合是基于哈希排序的(而不是基于插入的时间排序的)并且哈希值不会发生冲突(这就是为什么我使用小的数字和仅相差一个的数字)的顺序应该是确定性的,因为它们占据了集合内彼此相邻的插槽:

For integers that satisfy 0 <= integer < sys.hash_info.modulus the hash is just the number itself. That means if the set is ordered "based" on the hash (and not ordered based on the insertion "time") and the hash values don't collide (that's why I used small numbers and numbers that only differ by one) the order should be deterministic because they occupy slots inside the set that are next to each other:


  • 从最小到最高

  • 或a从特定值到最大值,然后从最小值到特定值。如果集合中的下一个(在邻近意义上)空闲插槽是第一个空闲插槽,则会发生这种情况。

后者:

>>> a_set = {6,7,8,9}
>>> a_set
{8, 9, 6, 7}

这篇关于集合是否像python3.6中的字典一样排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆