0

好的,所以我试图在堆栈中输入一个单词,我想在输入一个字符串后打印所有这些单词。所以我一次只能打印一个。我尝试在外面使用 for 循环,但 Stacks 显然不可迭代。所以我在堆栈中迭代它。它仍然无法正常工作。

class Stack:

    def __init__(self):
        self.items = []
    def push(self,items):
        self.items.insert(0,items)
    def pop(self):
        for x in self.items:
            print( self.items.pop(0))

    def show(self):
        print (self.items)

s = Stack()
s.show()
placed = input("enter")

item = s.pop()
print(item, "is on top", s)
4

1 回答 1

0

给你的Stack类一个__len__方法,这将使堆栈是否为空的测试更容易:

class Stack:
    def __init__(self):
        self.items = []

    def push(self,item):
        self.items.append(item)

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

    def show(self):
        print (self.items)

    def __len__(self):
        return len(self.items)

stack = Stack()

stack.push('World!')
stack.push('Hello')

while stack:  # tests the length through __len__
    print(stack.pop())

请注意,我只是简单地.append().items列表的末尾,然后.pop()(没有参数)再次从列表的末尾删除。

要使您的类成为可迭代类型,您至少需要添加一个__iter__方法,可选地与一个.__next__()方法一起添加:

class Stack:
    # rest elided

    def __iter__(self):
        return self

    def next(self):
        try:
            return self.items.pop()
        except IndexError:  # empty
            raise StopIteration  # signal iterator is done
于 2013-02-04T20:29:40.267 回答