好的,我试着在堆栈中输入一个单词,我想在输入一个字符串后打印所有的单词。所以我一次只能打印一个。我尝试在外部使用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)发布于 2013-02-05 04:29:40
给你的Stack类一个__len__ method,这将使测试堆栈是否为空变得更容易:
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() (没有参数)中再次从列表的末尾删除。
要使您的类成为an iterable type,您至少需要添加一个__iter__ method,也可以选择与一个.__next__() method一起添加
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 donehttps://stackoverflow.com/questions/14694834
复制相似问题