为什么在python中设置pop返回第一个元素而list pop返回最后一个元素 [英] Why set pop return first element while list pop return last element in python
问题描述
这有点令人困惑.它实际上来自堆栈 pop/push
术语吗?
L.pop([index]) -> item -- 删除并返回索引处的项目(默认最后).如果列表为空或索引超出范围,则引发 IndexError.
<预><代码>>>>[1,2].pop()2
<块引用>
删除并返回一个任意集合元素.如果设置,则引发 KeyError是空的.
<预><代码>>>>{1,2}.pop()1
set.pop
不不返回第一个元素.正如您引用的帮助中明确指出的那样,它返回一个任意元素.
原因很简单:集合本质上是无序的.没有有意义的第一个"或最后一个"元素.1
1.由于集合存储为哈希表,出于性能原因和简单性原因,set.pop
将删除哈希表中的第一个元素是有意义的,这通常与集合迭代的第一个元素相同,但不能保证.而且,事实上,CPython 3.6 - 3.7 和 3.3 - 3.5 中的确切时间是不同的.
It's a little bit confusing. Is it actually comes from stack pop/push
terminology?
L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
>>> [1,2].pop()
2
Remove and return an arbitrary set element. Raises KeyError if the set is empty.
>>> {1,2}.pop()
1
set.pop
does not return the first element. As it clearly says in the help that you quoted, it returns an arbitrary element.
And the reason for this is simple: sets are inherently unordered. There is no meaningful "first" or "last" element.1
1. Since sets are stored as hash tables, it makes sense for both performance reasons and simplicity reasons that set.pop
will remove the first element in the hash table, which will often be the same as the first element iterated by the set, but that's not guaranteed. And, in fact, exactly when it's true is different in CPython 3.6 - 3.7 than in 3.3 - 3.5.
这篇关于为什么在python中设置pop返回第一个元素而list pop返回最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!