python中列表和堆栈之间的区别?

pay*_*yal -1 python stack list

python中的列表和堆栈有什么区别?

我已经在python文档中阅读了它的解释但是两者似乎都是一样的?

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

堆栈是数据结构概念.该文档使用Python list对象来实现一个.这就是本教程的这一部分被命名为使用列表作为堆栈的原因.

堆栈只是你添加东西的东西,当你再次从堆栈中取出东西时,你会以相反的顺序,先进,最后的样式.就像一堆书或帽子或...... 啤酒箱:

啤酒箱堆放

请参阅维基百科的解释.

另一方面,列表更加通用,您可以在列表中的任何位置添加和删除元素.你不会尝试与一堆啤酒箱一起放在上面!

您可以使用自定义类实现堆栈:

from collections import namedtuple

class _Entry(namedtuple('_Entry', 'value next')):
    def _repr_assist(self, postfix):
        r = repr(self.value) + postfix
        if self.next is not None:
            return self.next._repr_assist(', ' + r)
        return r

class Stack(object):
    def __init__(self):
        self.top = None
    def push(self, value):
        self.top = _Entry(value, self.top)
    def pop(self):
        if self.top is None:
            raise ValueError("Can't pop from an empty stack")
        res, self.top = self.top.value, self.top.next
        return res
    def __repr__(self):
        if self.top is None: return '[]'
        return '[' + self.top._repr_assist(']')
Run Code Online (Sandbox Code Playgroud)

很难看到一个列表(有点人为),但绝对是一个堆栈:

>>> stack = Stack()
>>> stack.push(3)
>>> stack.push(4)
>>> stack.push(5)
>>> stack
[3, 4, 5]
>>> stack.pop()
5
>>> stack.push(6)
>>> stack
[3, 4, 6]
>>> stack.pop()
6
>>> stack.pop()
4
>>> stack.pop()
3
>>> stack
[]
Run Code Online (Sandbox Code Playgroud)

Python标准库没有特定的堆栈数据类型; 一个list对象就好了.只是将任何使用限制为list.append()list.pop()(后者没有参数)将列表视为堆栈.