【问题标题】:Why is this out of bounds? python为什么这是越界? Python
【发布时间】:2014-02-15 01:21:59
【问题描述】:
Enter expression:car.a + var.a
car   Variable
.   Variable
a   Variable
+   operator
var   Variable
.   Variable
a   Variable
Traceback (most recent call last):
  File "D:\My Documents\Python\Lexical analyzer.py", line 62, in <module>
    if(check_main(temp[i]) == 'Variable'):
IndexError: list index out of range

for i in range(1,len(temp),2):
if temp[i] == '.':
    if check_main(temp[i-1])=='Variable':
        temp[i-1:i+2]= [''.join(temp[i-1:i+2])]

列表是正确的 ['car.a', '+', 'var.a'] 但我不知道为什么它显示越界,抱歉我的英语不好

【问题讨论】:

  • 您没有向我们展示导致错误的代码,至少不是第 62 行附近的代码
  • 出错的行是if(check_main(temp[i]) == 'Variable'):,但这不在您向我们展示的代码中

标签: python indexoutofboundsexception


【解决方案1】:

它没有绑定,因为您在迭代列表长度时正在修改列表。问题出在这一行:

temp[i-1:i+2]= [''.join(temp[i-1:i+2])] 

在这里,您将曾经的三项更改为仅一项。因此,当您迭代它时,列表的长度实际上会缩短!很奇怪吧?在某一时刻,temp[i] 将不再有效,因为i 已经大于当前的len(temp)

你遇到了这样的事情:

>>> l = [1, 2, 3, 4, 5]
>>> l[1:4] = [1]
>>> l
[1, 1, 5]

解决方案?我建议您创建一个新列表,而不是修改列表。也许是这样的:

if check_main(temp[i-1])=='Variable':
    new_list.append(''.join(temp[i-1:i+2]))

希望这会有所帮助!

【讨论】:

  • @user3199813 不客气!如果您认为此答案有帮助,请接受。
猜你喜欢
  • 2012-11-08
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多