【问题标题】:IndexError: list index out of range,but it does notIndexError:列表索引超出范围,但它没有
【发布时间】:2019-07-28 06:47:02
【问题描述】:
def change(txt):    
    for i in range(9):
        k=len(txt[i])
        for j in range(k):

            if txt[i][j-1]=='6':
                txt[i].pop(j)
            if '\n' in txt[i]:
                txt[i].remove('\n')
        k=0
change(sd)

这表明: 如果 txt[i][j-1]=='6': IndexError: 列表索引超出范围

txt 是一个嵌套列表

我改成 定义更改(txt): s=len(txt) 对于我在范围内: k=len(txt[i]) 打印(k) 对于范围内的 j (k): 如果 txt[i][j].isdigit: 如果 txt[i][j-2].isdigit: 删除 txt[i][j-1] 如果 '\n' 在 txt[i] 中: txt[i].remove('\n') 如果 txt[i][j]==',': txt[i][j]=='.' k=0

同样的错误

【问题讨论】:

  • 而且 txt 肯定有 len 9。
  • 我在范围内为 i 添加 s=len(txt):仍然给我同样的错误
  • [[',', ',', ',', ',', ',', '6', ',', ',', ',', '\n' ], [',', '5', ',', '9', ',', ',', ',', ',', ',', ',', '8', '\n '], ['2', ',', ',', ',', ',', ',', '8', ',', ',', ',', '\n'], [',', '4', ',', '5', ',', ',', ',', ',', ',', ',', '\n'], [', ', ',', '3', ',', ',', ',', ',', ',', ',', '\n'], [',', ',', ' 6', ',', ',', ',', '3', ',', ',', '5', ',', '4', '\n'], [',', ',', ',', '3', ',', '2', ',', '5', ',', ',', ',', '6', '\n'], [',', '5', ',', ',', ',', ',', ',', ',', ',', '\n'], [',', ', ', ',', ',', ',', ',', ',', ',', '\n']] 这是txt
  • 我想把 '6' 改成 '1','2','3','4','5','6','7','8'and' 9' .我该怎么做呢
  • 请不要在 cmets 中乱涂乱画。 Edit您的问题以添加详细信息。

标签: python list indexing


【解决方案1】:

您正在使用[j - 1],它指向一个不在列表中的索引。将代码从for j in range(k)更改为for j in range(k-1)

【讨论】:

  • 这是j - 1,而不是j + 1。在这里将范围更改为 k-1 有何帮助?
  • ` for j in range(k)` --> ` for j in range(k-1)`
  • 如果 txt[i][j]=='6' 不会改变:IndexError: list index out of range
  • 如果最小的 j-1 是 -1 仍然在列表中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多