-
Notifications
You must be signed in to change notification settings - Fork 52.1k
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
Comments
set概念上是无序的。
但是调用set1实际是调用了rang()函数,range()函数是有序的。
而set2作为空集来存储输出结果,表现了set的无序性。
应该是这样?
|
set1的有序性可以理解,因为range()函数是有序的。
|
set1表现的有序可能是range函数的功劳,或者单纯的因为是连续整数的原因。
set2是通过add()操作完成的加元素,而add()不是说添加在集合末尾。
set是不包含value的,所以也没有明确大小关系,只能达到去重的作用。而且这个应该与set底层实现逻辑有关,Hashset这个概念。
希望有序结构就使用list。
…On Sun, Sep 8, 2019, 6:23 PM admirewhat ***@***.***> wrote:
set1的有序性可以理解,因为range()函数是有序的。
但是set2的add的过程也是有序进行的啊,为什么add的位置是随机的呢?
set概念上是无序的。 但是调用set1实际是调用了rang()函数,range()函数是有序的。
而set2作为空集来存储输出结果,表现了set的无序性。 应该是这样?
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#301?email_source=notifications&email_token=ALESCLJLCHOYB6RI3VTXKALQITHDLA5CNFSM4IUSWEAKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6FMSSQ#issuecomment-529189194>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/ALESCLJB2U2DA7IJN3IK3FTQITHDLANCNFSM4IUSWEAA>
.
|
按理是这样的,但是set有个pop函数,它总是pop掉集合的第一个函数,这样看来集合内的顺序有时确实是有关系的(可能还有其他函数的操作也跟集合内元素的顺序有关,我因为不熟所以不能一一举例) |
我是觉得这是绕进去了。
set会自动排序,但是不清楚自动排序规则,尝试了很多组合吧,连续整数情况下是刚好符合连续性和规整性,当数字变动极大的时候直接表现"无序",但是这个不是真的无序,同样的组合得出的顺序是一致的。你可以了解一下hash算法,这里的无序和hash算法原理应该差不多,是为了实现快速去重。想要知道实现过程就只有扒底层代码了。
pop()是会从左移出第一个元素,但是是经过set自动重排后的第一个元素,对初始状态而言是无序了。
add()原则上同理,从最右端加入一个元素,然后set完成自动重排,在用print()输出时结果为无序。
无序性是由set自身底层逻辑完成的,和pop(), add()应该没有关系。这两个功能应该是用链表逻辑实现的。
… —
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#301?email_source=notifications&email_token=ALESCLKJZRTEF7TUO2GCDFDQIUDTPA5CNFSM4IUSWEAKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6FRAQA#issuecomment-529207360>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/ALESCLPPRMHLKL6NHZ3Y3QLQIUDTPANCNFSM4IUSWEAA>
.
|
欧克 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
在练习集合的时候,发现一个无法理解也无法解决的集合内元素的排序问题,望有大神帮忙解释一下
我从一个顺序的集合,通过平方的关系生成一个新的集合,为什么新集合的元素排序和原来的集合毫无关系?
代码如下
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的过程中,新元素的位置完全是随机的,这是什么原因?
The text was updated successfully, but these errors were encountered: