首页 > 解决方案 > IndexError:Python中的列表分配索引超出范围

问题描述

我正在尝试实现堆栈操作:

如果我尝试避免使用 .append() 并使用 self.size 进行索引并返回大小而不是使用 len(self.stack) 它会抛出这个:

Traceback (most recent call last):
  File "C:\Users\user\Downloads\UPN.py", line 62, in <module>
    print(round(test.upn(notation))
  File "C:\Users\user\Downloads\UPN.py", line 50, in upn
    self.push(float(el))
  File "C:\Users\user\Downloads\UPN.py", line 16, in push
    self.stack[self.size+1] = x
IndexError: list assignment index out of range
[]

Process finished with exit code 1

代码片段:

from time import sleep

class Stack:
    def __init__(self):
        self.stack = []
        self.size = 0
        self.operatoren = {
            "+": (lambda a, b: a + b),
            "-": (lambda a, b: a - b),
            "*": (lambda a, b: a * b),
            "/": (lambda a, b: a / b)
        }

    def push(self, x):
        self.stack[self.size-1] = x
        self.size += 1
    
    def top(self):
        return self.stack[self.size-1]
    
    def pop(self):
        self.size -= 1
        return self.stack.pop()
    
    def isEmpty(self):
        return not self.stack
    
    def size(self):
        return self.size
    
    def upn(self, expression):
        elemente = expression.split()
    
        for el in elemente:
            print(self.stack)                               
            if el not in self.operatoren:
                self.push(float(el))
            else:
                zahl2 = self.pop()
                zahl1 = self.pop()
                ergebnis = self.operatoren[el](zahl1, zahl2)
                self.push(ergebnis)
    
        return self.pop()


test = Stack()
notation = "5.1 91 28 + 4.3 6 + * 777 + *"
print(round(test.upn(notation)))

标签: pythonstack

解决方案


在“堆栈”类中:

class Stack:
    ...

    def push(self, x):
        self.stack[self.size-1] = x ##### target #####
        self.size += 1

    ...

在目标行:

... self.size = 0 and self.stack[self.size-1] = x ->
... self.stack[0-1] = x
... self.stack[-1] = x

所以self.stack[self.size] = x和:

class Stack:
    ...

    def push(self, x):
        self.stack[self.size] = x
        self.size += 1

    ...


推荐阅读