为什么python列表有pop()而没有push()

2024-03-28 22:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道为什么Python的list.append函数不被称为list.push,因为已经有一个list.pop删除并返回最后一个元素(索引在-1处),并且list.append语义与该用法一致吗?


Tags: 函数元素用法语义poppushlistappend
3条回答

因为它是附加物;它不会推动。”在列表的末尾加上“adds”,在前面加上“push”。

想象一个队列和一个堆栈。

http://docs.python.org/tutorial/datastructures.html

编辑:要更准确地改写我的第二句话,“追加”非常清楚地意味着向列表的结尾添加一些内容,而不考虑底层实现。当一个新元素被“推”时,它被添加到哪里就不那么清楚了。推到堆栈上就是把一些东西放在“顶部”,但它在底层数据结构中的实际位置完全取决于实现。另一方面,推到队列上意味着将其添加到末尾。

因为它在列表中附加了一个元素?当提到堆栈时,通常使用Push。

因为“附加”早在“流行”之前就存在了。Python 0.9.11991年初支持list.append。相比之下,这里是关于1997年添加pop的discussion on comp.lang.python部分内容。圭多写道:

To implement a stack, one would need to add a list.pop() primitive (and no, I'm not against this particular one on the basis of any principle). list.push() could be added for symmetry with list.pop() but I'm not a big fan of multiple names for the same operation -- sooner or later you're going to read code that uses the other one, so you need to learn both, which is more cognitive load.

您还可以看到,他讨论了push/pop/put/pull应该在元素[0]处还是在元素[-1]之后,在元素[1]处发布对图标列表的引用:

I stil think that all this is best left out of the list object implementation -- if you need a stack, or a queue, with particular semantics, write a little class that uses a lists

换句话说,对于已经支持fast append()和del list[-1]的直接实现为Python list的堆栈,list.pop()在默认情况下对最后一个元素起作用是有意义的。即使其他语言做得不一样。

这里隐含的是,大多数人需要追加到列表中,但很少有人有机会将列表视为堆栈,这就是为什么list.append来得更早。

相关问题 更多 >