程序中出現list assignment index out of range的解決方法


class stack:

def __init__(self):
self.num = 0
self.elem=[]

def isEmoty(self):
if self.num == 0:
print('空棧')
else:
print('這個棧有%d個元素'%self.num)

def push(self,x):
self.elem[self.num] = x
self.num+=1

def pop(self,):
self.num-=1

def top(self):
print(self.elem[self.num-1])

運行程序的時候 ,會出現list assignment index out of range的錯誤,原因是push函數用了列表零元素elem[]但是這個元素並不存在。
解決方法,用lish內置函數append來添加元素。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM