简体   繁体   English

为什么Python按顺序打印一组数字

[英]Why does Python print a set of numbers as ordered

I tried print this in the python idle {6,3,7}.我尝试在 python 空闲 {6,3,7} 中打印此内容。 The output was {3,6,7}. output 是 {3,6,7}。 Shouldn't sets be unordered and print a different order each time?集合不应该是无序的并且每次都打印不同的顺序吗? Is it something related to the way hash maps are built?是否与 hash 地图的构建方式有关?

Sets are indeed unordered in Python. Python 中的集合确实是无序的。 The fact that your particular example set happens to give elements in apparently sorted order when iterated over (and appears reproducible in python 2.7.6 and 3.4.3) does not negate this fact, and another example gives elements in an order which is neither the order in which they were added to the set, nor is it sorted.您的特定示例集恰好在迭代时以明显排序的顺序给出元素(并且在 python 2.7.6 和 3.4.3 中似乎可重现)这一事实并不能否定这一事实,另一个示例以既不是它们被添加到集合中的顺序,也不是排序的。

>>> list(set([6,3,7]))
[3, 6, 7]

>>> list(set([6,3,8]))
[8, 3, 6]

For the values 6, 3 and 8, the order in which iteration over a python set containing those values will yield elements does at least appear to be consistent, regardless of the order in which the set was populated.对于值 6、3 和 8,在包含这些值的 python 集合上的迭代将产生元素的顺序至少看起来是一致的,无论填充集合的顺序如何。 However, this says nothing about whether this result is generally true, and in any case it should be considered an implementation detail.然而,这并没有说明这个结果是否普遍正确,无论如何它应该被视为一个实现细节。 User code should not assume any ordering at all.用户代码根本不应假定任何排序。

>>> from sympy.utilities.iterables import multiset_permutations
>>> for p in multiset_permutations([3,6,8]): print(p, list(set(p)))
... 
([3, 6, 8], [8, 3, 6])
([3, 8, 6], [8, 3, 6])
([6, 3, 8], [8, 3, 6])
([6, 8, 3], [8, 3, 6])
([8, 3, 6], [8, 3, 6])
([8, 6, 3], [8, 3, 6])

See, I understand your concern, and I was confused in the beginning as well, when I first saw it.看,我理解你的担心,当我第一次看到它时,我一开始也很困惑。 But I am certain you know sets are unordered and unindexed.但我敢肯定,你知道集合是无序和无索引的。 Hence it cannot be the case that the elements of any set are ordered.因此,任何集合的元素都不可能是有序的。 Try running something like a = {6,2,90,4,12,0,4000,345} or your example -- on Jupyter Notebook, or on IDLE or through command prompt.尝试运行类似a = {6,2,90,4,12,0,4000,345}或您的示例 - 在 Jupyter Notebook、IDLE 或通过命令提示符。 It's arranged differently.它的排列方式不同。

On Jupyter, it gave: {0, 2, 4, 6, 12, 90, 345, 4000}在 Jupyter 上,它给出: {0, 2, 4, 6, 12, 90, 345, 4000}

On Command Prompt: {0, 4000, 2, 4, 6, 12, 345, 90}在命令提示符下: {0, 4000, 2, 4, 6, 12, 345, 90}

And when you print the elements of a set one by one, it will be shown in the order:而当你一个一个地打印一个集合的元素时,它会按顺序显示:

4000
2
4
6
12
345
90

I believe you were trying on Jupyter.我相信您正在尝试使用 Jupyter。 They always seem to sort it when you want to see a variable like a , here.当您想在这里看到像a这样的变量时,它们似乎总是对其进行排序。

And for your doubt, hash map concept applies to dictionaries, and not to sets.对于您的疑问,hash map 概念适用于字典,而不适用于集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM