问题
This is the strange thing I noticed in Python sets. I read there is no order in sets, but it does pop lower elements from 0 till 79 and later from 79 till 127. It does not pop the lower ones any more. Only after 128 comes in 79 is popped. Why is it like this?
Is there any alternative where I can use the ordered data structure in Python? Why is it popping the lowest from 0 till 79 and not from 79 till 127?
>>s = set()
>>s.add(72)
>> s.add(74)
>> s.add(76)
>> s.pop()
72
>> s.add(79)
>> s.pop()
74
>> s.add(81)
>> s
set([81, 76, 79])
>> s.pop()
76
>> s.add(83)
>> s
set([81, 83, 79])
>> s.add(85)
>> s
set([81, 83, 85, 79])
>> s.pop()
81
>> s
set([83, 85, 79])
回答1:
There is a "consistent" internal ordering depending on the insertion and removal of elements in dictionaries. See: http://docs.python.org/library/stdtypes.html#dict.items
As far as I'm aware sets use the same hashing implementation and will most likely have the same ordering effects.
回答2:
Why is it popping the lowest from 0 till 79 and not from 79 to 128 ?
Well no , the ordering is not random but it's completely arbitrary. There's is no specific ordering in python sets. Consider this :
>>> s.add(14)
>>> s.add(11)
>>> s.add(3)
>>> s.add(13)
>>> s.add(2)
>>> s.pop()
13
>>> s.pop()
14
>>> s.pop()
2
>>> s.pop()
3
>>> s.pop()
11
This isn't complying to your conclusion.( this time it happens for 14 )
来源:https://stackoverflow.com/questions/12005436/python-sets-pop-behaviour