Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

集合排序的问题 #301

Open
admirewhat opened this issue Sep 8, 2019 · 6 comments
Open

集合排序的问题 #301

admirewhat opened this issue Sep 8, 2019 · 6 comments

Comments

@admirewhat
Copy link

在练习集合的时候,发现一个无法理解也无法解决的集合内元素的排序问题,望有大神帮忙解释一下
我从一个顺序的集合,通过平方的关系生成一个新的集合,为什么新集合的元素排序和原来的集合毫无关系?
代码如下
set1 = set(range(1, 10))
print(set1)
set2 = set()
for elem in set1:
print(elem)
set2.add(elem ** 2)
print(set2)

执行结果如下
{1, 2, 3, 4, 5, 6, 7, 8, 9}
1
{1}
2
{1, 4}
3
{1, 4, 9}
4
{16, 1, 4, 9}
5
{1, 4, 9, 16, 25}
6
{1, 4, 36, 9, 16, 25}
7
{1, 4, 36, 9, 16, 49, 25}
8
{64, 1, 4, 36, 9, 16, 49, 25}
9
{64, 1, 4, 36, 9, 16, 49, 81, 25}

可以看到即使set1是有序的,在生成set2的过程中,新元素的位置完全是随机的,这是什么原因?

@jeffforfun
Copy link

jeffforfun commented Sep 8, 2019 via email

@admirewhat
Copy link
Author

set1的有序性可以理解,因为range()函数是有序的。
但是set2的add的过程也是有序进行的啊,为什么add的位置是随机的呢?

set概念上是无序的。 但是调用set1实际是调用了rang()函数,range()函数是有序的。 而set2作为空集来存储输出结果,表现了set的无序性。 应该是这样?

@jeffforfun
Copy link

jeffforfun commented Sep 8, 2019 via email

@admirewhat
Copy link
Author

按理是这样的,但是set有个pop函数,它总是pop掉集合的第一个函数,这样看来集合内的顺序有时确实是有关系的(可能还有其他函数的操作也跟集合内元素的顺序有关,我因为不熟所以不能一一举例)
这个跟集合内元素的乱序在逻辑上其实是冲突的。

@jeffforfun
Copy link

jeffforfun commented Sep 8, 2019 via email

@XinlangChen
Copy link

欧克

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants