简体   繁体   English

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

[英]how to print elements of a stack in python 3

I have to print elements in a stack using classes and all:我必须使用类和所有在堆栈中打印元素:

class Stack:

    def __init__(self):
        self.stack = []

    def push(self,element):
        self.stack.append(element)

    def pop(self):
        return self.stack.pop()

def st(n):

    s = Stack()
    for i in range(n,0,-1):
        s.push(i)

    #this is updated version now I want to print outside of the loop and 
    #it gives me this error : __main__.Stack instance at 0x7fe40d261710> 
    print s
if __name__ == '__main__':

   st(4)

for some reason instead of printing [4,3,2,1] it print None出于某种原因而不是打印 [4,3,2,1] 它打印无

Your class does not define __str__ or __repr__ method, so print uses the default representation.您的类没有定义__str____repr__方法,因此print使用默认表示。 If you want instances of Stack to be printed as lists, add the following definition to your class:如果要将Stack实例打印为列表,请将以下定义添加到您的类中:

def __str__(self):
    return str(self.stack)

Stask class using built-ins使用内置函数的 Stask 类

Using lists as stack https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks使用列表作为堆栈https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks

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().要将项目添加到堆栈顶部,请使用 append()。 To retrieve an item from the top of the stack, use pop() without an explicit index要从堆栈顶部检索项目,请使用不带显式索引的 pop()

If you have to provide custom interface for adding elements in stack you can add single method like this:如果您必须提供用于在堆栈中添加元素的自定义界面,您可以添加这样的单个方法:

class Stack(list):
    def push(self, *args, **kwargs):
        self.append(*args, **kwargs)

Printing objects打印对象

How print function behave? print功能如何表现?

Lets look at documentation about print function https://docs.python.org/3/library/functions.html#print让我们看看有关print功能的文档https://docs.python.org/3/library/functions.html#print

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.所有非关键字参数都像 str() 那样转换为字符串并写入流,由 sep 分隔,后跟 end。

What str() function really does? str()函数到底做了什么?

If neither encoding nor errors is given, str(object) returns object.__str__() , which is the “informal” or nicely printable string representation of object.如果既没有给出编码也没有给出错误,则 str(object) 返回object.__str__() ,这是object.__str__()“非正式”或可很好打印的字符串表示。 For string objects, this is the string itself.对于字符串对象,这是字符串本身。 If object does not have a __str__() method, then str() falls back to returning repr(object) .如果 object 没有__str__()方法,则 str() 回退到返回repr(object)

This means that you Stack have to support __str__() method, and if it has no such __repr__() will be used.这意味着你的Stack必须支持__str__()方法,如果它没有这样的__repr__()将被使用。

Look at repr(object) docs if you didn't believe my words https://docs.python.org/3/library/functions.html#repr如果您不相信我的话,查看repr(object)文档https://docs.python.org/3/library/functions.html#repr

A class can control what this function returns for its instances by defining a repr () method.类可以通过定义repr () 方法来控制此函数为其实例返回的内容。

Also read this answers, which describe my thoughts in different manner:另请阅读此答案,它们以不同的方式描述了我的想法:

Summary概括

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)
print s.push(i)

See the line, s.push() append the value and returns None .请参阅行, s.push()附加值并返回None So you end up printing None所以你最终打印None

Your pop() works, because unlike append() , it returns a value.您的pop()有效,因为与append()不同,它返回一个值。

So, change the function definition like that:因此,像这样更改函数定义:

def push(self,element):
    self.stack.append(element)
    return self.stack 
return "".join(self.stack_objects)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM