python3堆栈_如何在python 3中打印堆栈元素

本文介绍了如何利用Python内置的List类实现堆栈操作,重点在于`append()`方法用于压栈和`pop()`方法用于弹栈。当需要自定义堆栈接口时,可以通过创建Stack类并重写`push()`方法。此外,还讨论了`__str__()`方法的重要性,用于返回堆栈的字符串表示,确保输出符合堆栈的“后进先出”原则。示例代码展示了如何初始化堆栈、添加元素以及打印堆栈内容。
摘要由CSDN通过智能技术生成

使用内置的Stask类The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index

如果必须为在堆栈中添加元素提供自定义接口,则可以添加以下单个方法:class Stack(list):

def push(self, *args, **kwargs):

self.append(*args, **kwargs)

打印对象

函数如何工作?All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

函数真正的作用是什么?If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).

这意味着您Stack必须支持__str__()方法,如果它没有这样的__repr__()将被使用。A class can control what this function returns for its instances by defining a repr() method.

也请阅读以下答案,它们以不同的方式描述了我的想法:

摘要class Stack(list):

"""

Implaments stack interface to access data by inheriting buil-in list

object.

Note: all parent methods will be accessable in stack instance.

"""

def push(self, *args, **kwargs):

"""

Delegate behaviour to parrent class.

"""

self.append(*args, **kwargs)

def __str__(self):

"""

Because of using list as parent class for stack, our last element will

be first for stack, according to FIFO principle. So, if we will use

parent's implementation of str(), we will get reversed order of

elements.

"""

#: You can reverse elements and use supper `__str__` method, or

#: implement it's behavior by yourself.

#: I choose to add 'stack' in the begging in order to differ list and

#: stack instances.

return 'stack [{}]'.format(', '.join(reversed(self)))

def example_of_usage():

#: Here we just using parent's list initialization functionality to init

#: stack from iterable (in our case - list).

s = Stack(['last', 'first'])

#: output> stack ['fist', 'last']

print(s)

s.push('very first')

#: output> stack ['very first', 'fist', 'last']

print(s)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值