Python 堆栈迭代蟒蛇3

Python 堆栈迭代蟒蛇3,python,list,python-3.x,iterator,stack,Python,List,Python 3.x,Iterator,Stack,好的,我试着在堆栈中输入一个单词,我想在输入一个字符串后打印所有单词。所以我一次只能打印一张。我尝试在外部使用for循环,但堆栈显然不适合。所以我在堆栈中迭代它。它仍然不起作用 class Stack: def __init__(self): self.items = [] def push(self,items): self.items.insert(0,items) def pop(self): for x in se

好的,我试着在堆栈中输入一个单词,我想在输入一个字符串后打印所有单词。所以我一次只能打印一张。我尝试在外部使用for循环,但堆栈显然不适合。所以我在堆栈中迭代它。它仍然不起作用

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)

堆栈设置为a类,这将使测试堆栈是否为空变得更容易:

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()
(无参数)中再次从列表的末尾删除

要创建您的类,您需要至少添加一个,还可以添加一个:


关于堆栈设计,为什么不使用
.append()
.pop()
?将项目添加到列表的末尾,然后不带任何参数的
.pop()
再次将其从末尾删除。好的,等等,如何向后打印Hello?这就是为什么我需要迭代?好的,我知道了,你只需要这个。返回self.\u items[len(self.\u items)-1]只需使用
[-1]
;选择最后一个索引为负数的元素。
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