Python错误列表索引超出范围

标签 python indexing

我知道这是一个新手问题,但我不断收到通常不会收到的错误。 “索引错误:第 12 行的列表索引超出范围。”其中写着 2 个“nums”。我认为在循环之外调用变量完全没问题吗?

lisp = []
new = []

for x in range(1, 11):
    num = int((x * (3*x - 1))/2)
    lisp.append(num)

x = 0
y = 2

for i in lisp[1:]:
    num1 = lisp[x] + i
    num2 = lisp[y] + i
    dif1 = i - lisp[x]
    dif2 = lisp[y] - i
    smallList = [num1, num2, dif1, dif2]
    new.append(smallList)

    x += 1
    y += 1

print(new)

最佳答案

使用ipython修复。

脚本.py:

lisp = []
new = []

for x in range(1, 11):
    num = int((x * (3*x - 1))/2)
    lisp.append(num)

x = 0
y = 2

for i in lisp[1:]:
    num1 = lisp[x] + i
    num2 = lisp[y] + i
    dif1 = i - lisp[x]
    dif2 = lisp[y] - i
    smallList = [num1, num2, dif1, dif2]
    new.append(smallList)

    x += 1
    y += 1

print(new)

启动ipython并执行以下操作:

In [1]: run script.py
     11 for i in lisp[1:]:
     12     num1 = lisp[x] + i
---> 13     num2 = lisp[y] + i
     14     dif1 = i - lisp[x]
     15     dif2 = lisp[y] - i

IndexError: list index out of range

In [2]: y
Out[2]: 10

In [3]: len(lisp)
Out[3]: 10

这里y = 10,但是len(lisp) = 10有效索引在09之间(均包含在内,从 0 开始)并且 10 超出此范围。

关于Python错误列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44756009/

相关文章:

python - Sphinx Autodoc 从文档字符串中跳过成员

python - 在python中循环遍历文本文件时出错

python - 列表列表转换为 pandas DataFrame

C++ 在索引删除硬编码数字列表中的位置

python - 带有gunicorn和nginx的Django不会返回404或500

python - 在python中是否可以编写一个在子类的__init__之后自动调用的方法

java - 如何在 lucene 中索引 pdf、ppt、xl 文件(基于 java 或 python 或 php 的任何一个都可以)?

r - 从 R 中的 "key"获取 "value"

MySQL 索引 : Why does multi-column index perform worse than single column index?

database - 了解 Cloud Spanner INDEX(索引)中的 INTERLEAVE