【问题标题】:Why won't my list populate? IndexError: List Out of Range为什么我的列表不会填充? IndexError:列表超出范围
【发布时间】:2013-12-06 10:19:39
【问题描述】:

阅读 Stacks,所以我尝试了这个 Infix to Postfix 练习(找到 here)。你必须滚动一点才能看到他们的代码。我试图尽可能忠实于他们最初的实现。

我的代码:http://pastebin.com/dG4Ku14n

我在第 18 行(我在其中定义 peek 变量)遇到错误。它说列表超出范围但我不应该调用列表吗?当我在第 49 行使用“prec[peek]”时,它不应该只是存储在变量中,实际错误应该出现在文档的后面吗?

我确信这段代码比我想象的更有趣。任何帮助,将不胜感激。我应该重新开始吗?

短版:

peek = operator_stack[len(operator_stack)-1]
for element in infix:
    if:
        #code
    else:
    while not operator_stack and prec[peek] >= prec[element]:
        output_queue.append(operator_stack.pop())
    operator_stack.append(element)

预期输出:

A B * C + D *

【问题讨论】:

  • 请将您的代码缩减为short, self-contained, correct example 并将其直接包含在问题中。
  • 请发布您的预期输出
  • 添加了预期输出
  • @pope 我想虽然你 tried to stay as true to their original implementation as possible. 它并没有那样发生:(

标签: python python-3.x stack


【解决方案1】:

不幸的是,operator_stack 列表为空,因此如果您想查找列表的最后一个元素,它会返回 IndexError BTW,如果它为空,请确保将其设为 None:

所以使用:

peek = operator_stack[-1] if operator_stack else None

代替:

peek = operator_stack[len(operator_stack)-1]

此外,在调试代码时,从 cmets 中可以清楚地看到这些行:

第 49 行:while not operator_stack and prec[peek] >= prec[element]:

第 59 行:while not operator_stack:

实际上应该是这样的:

第 49 行:while operator_stack and prec[peek] >= prec[element]:

第 59 行:while operator_stack:

最后添加一个if语句来检查peek是否为None

一个简短的版本是

#line 18
peek = operator_stack[-1] if operator_stack else None
#line 49
if peek is not None:
    while operator_stack and prec[peek] >= prec[element]:

            #Append the pop'd element of the operator stack to the
            #output_queue list.
            output_queue.append(operator_stack.pop())

    #Append whatever is left (+,-,*,/) to the operator stack
    operator_stack.append(element)

    #line 59
    while operator_stack:
            #Append the last element in the stack until the stack is empty.
            output_queue.append(operator_stack.pop())

如果你doubtwhile operator_stack: 是什么意思,请看这个简单的例子:

>>> a = [2,5,6]
>>> while a: # a is not empty right?
...     print 2 # so print 2
...     break # and break
2

【讨论】:

  • 没有帮助,因为堆栈是空的。
  • @MarkRansom 刚刚注意到
  • peek = (operator_stack[-1:] + [None])[0] 呢?
  • 谢谢。我将不得不在一个小时左右的时间内对此进行测试,如果它有效,我会检查你的答案!但我有个问题。 while operator_stack ... 是否意味着它不是空的?这就是我想要的。
  • @pope 只是为了事实:你不是用operator_stack = []替换opStack = Stack()
猜你喜欢
  • 2018-10-31
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2015-06-26
  • 1970-01-01
相关资源
最近更新 更多