【问题标题】:IndexError with matplotlib索引错误与 matplotlib
【发布时间】:2017-07-22 16:37:25
【问题描述】:

我一直在尝试使用这段代码来绘制 C 曲线 (https://en.wikipedia.org/wiki/Lévy_C_curve),但不知何故它一直给我这个错误:

IndexError: list index out of range

但是列表的长度对我来说似乎没问题,因为它设置为 n-1,那么为什么这个错误一直出现?

不久前,当我尝试类似的东西(Sierprinski 三角形)时,我遇到了同样的问题,所以我非常感谢一些帮助。

import matplotlib.pyplot as plt
from math import *

def DrawC(direction, length, n):
    """Drawing the curve."""

    if n > 0:
        direction = direction + (pi / 4.0)
        DrawC(direction, length / sqrt(2.0), n-1)
        direction = direction - (pi / 2.0)
        DrawC(direction, length / sqrt(2.0), n-1)
    else:
        x = x_lst[-1] + length * cos(direction)
        y = y_lst[-1] + length * sin(direction)
        x_lst.append(x)
        y_lst.append(y)

n = int(raw_input('Generation of the curve: '))

x_lst = []
y_lst = [-150]


direction = pi / 2
length = 300
DrawC(direction, length, n)

plt.plot(x_lst, y_lst)
plt.title("C-curve")
plt.axis([-350, 350, -350, 350])
plt.show()

raw_input('Push the ENTER key: ')

【问题讨论】:

  • 该错误是否与任何特定的代码行有关?你之前是怎么解决这个问题的?
  • 是的,它指的是第 9 行(两次)、13 和 26 行。实际上还没有解决另一行。

标签: python recursion matplotlib index-error


【解决方案1】:

列表x_lst 不应为空。

无论您的代码采用什么路径,当x = x_lst[-1] + length * cos(direction) 时,列表不能为空。这是有道理的,因为您正在构建一个点列表,因此例如,从[0] 开始为x_lst。无论如何,这给了我很好的照片:-)

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2023-01-21
    • 2015-11-22
    • 2019-04-01
    • 1970-01-01
    • 2019-11-06
    • 2014-10-30
    • 2019-10-22
    相关资源
    最近更新 更多