如果集合是无序的,为什么集合以相同的顺序显示? [英] Why does a set display in same order if sets are unordered?

查看:86
本文介绍了如果集合是无序的,为什么集合以相同的顺序显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先从 Python wikibook 中了解 Python 语言.>

对于集合,提到了以下内容:

<块引用>

我们还可以在集合中的每个项目上循环移动.然而,由于集合是无序的,迭代将遵循的顺序是不确定的.

给出的代码示例是:

s = set("bleger")对于 s 中的字母:打印信

输出:

 r b e l g

当我运行程序时,无论我运行多少次,我都会以相同的顺序获得结果.如果集合是无序的且迭代顺序未定义,为什么它以相同的顺序返回集合?订单的依据是什么?

解决方案

它们不是随机排列的,它们是任意排列的.这意味着您不应该指望维护的插入顺序,因为实际的内部实现细节决定了顺序.

顺序取决于集合的插入和删除历史.

在 CPython 中,集合使用哈希表,其中插入的值根据从 hash() 函数返回的值插入一个稀疏表,以表大小和冲突处理算法为模.列出设置的内容然后返回在此表中排序的值.

如果您想了解详细的技术细节,请查看 为什么字典和集合中的顺序是任意的?;集合的核心是字典,其中键是 set 值,并且没有关联的字典值.与往常一样,实际的实现稍微复杂一些,但该答案足以让您完成大部分工作.然后看set的C源代码 其他细节.

将此与列表进行比较,列表具有您可以影响的固定顺序;您可以在列表中移动项目,并为您维护新的排序.

I'm taking a first look at the python language from Python wikibook.

For sets the following is mentioned:

We can also have a loop move over each of the items in a set. However, since sets are unordered, it is undefined which order the iteration will follow.

and the code example given is :

s = set("blerg")

for letter in s:
     print letter

Output:

 r b e l g

When I run the program I get the results in the same order, no matter how many times I run. If sets are unordered and order of iteration is undefined, why is it returning the set in the same order? And what is the basis of the order?

解决方案

They are not randomly ordered, they are arbitrarily ordered. It means you should not count on the order of insertions being maintained as the actual internal implementation details determine the order instead.

The order depends on the insertion and deletion history of the set.

In CPython, sets use a hash table, where inserted values are slotted into a sparse table based on the value returned from the hash() function, modulo the table size and a collision handling algorithm. Listing the set contents then returns the values as ordered in this table.

If you want to go into the nitty-gritty technical details then look at Why is the order in dictionaries and sets arbitrary?; sets are, at their core, dictionaries where the keys are the set values and there are no associated dictionary values. The actual implementation is a little more complicated, as always, but that answer will suffice to get you most of the way there. Then look at the C source code for set for the rest of those details.

Compare this to lists, which do have a fixed order that you can influence; you can move items around in the list and the new ordering would be maintained for you.

这篇关于如果集合是无序的,为什么集合以相同的顺序显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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