首页 > 解决方案 > 填充多边形,列表超出范围

问题描述

我正在尝试从 csv 文件填充多边形,我正在使用以下代码,并且出现问题y.append(str(row[1]))

IndexError:列表索引超出范围“

代码:

    import matplotlib.pyplot as plt
    import csv

    x = []
    y = []
    # coord = [[1,1], [2,1], [2,2], [1,2],]
    with open('screen.txt','r') as csvfile:
        coord = csv.reader(csvfile, delimiter=',')
        for row in coord:
            x.append(str(row[0]))
            y.append(str(row[1]))

    coord.append(coord[0]) #repeat the first point to create a 'closed loop'

    xs, ys = zip(*coord) #create lists of x and y values

    plt.figure()
    plt.plot(xs,ys)
    plt.fill(xs, ys, color= "r")
    plt.show()

标签: pythonmatplotlib

解决方案


问题中的代码假设文件“screen.txt”如下所示:

1,1
2,1
2,2
1,2

然后,您创建一个变量coords,这会_csv.reader object在随后的代码中表现得好像coords是一个简单的列表。reader 对象是读取文件的特殊对象,并允许构造为for row in coords. 但它只在需要时读取文件的一部分(以防止在您只需要几行时读取数百万行的情况)。关闭文件后(即在 之后with open(...),阅读器对象变得不可用。

作为简单的解决方法,如果文件不是很长,您可以将坐标转换为列表:coords = list(coords). 从那时起,它就可以用作普通列表了。

顺便说一句,如果文件如上所述,list index out of range则会为 line 引发错误coord.append(coord[0])

另一个可能的原因可能是您的输入文件末尾包含空行。然后你会得到第一个错误,x.append(str(row[0]))或者y.append(str(row[1]))如果最后一行只包含几个空格。但是删除空行后,您仍然会在coord.append(coord[0])

修改后的代码(省略列表 x 和 y,因为它们在此版本中并未真正使用):

import csv
from matplotlib import pyplot as plt

# coord = [[1,1], [2,1], [2,2], [1,2],]
with open('screen.txt', 'r') as csvfile:
    coord = csv.reader(csvfile, delimiter=',')
    coord = list(coord)  # we can step out of the 'with', because the file isn't needed
                         # anymore once we have the real list

coord.append(coord[0])  # repeat the first point to create a 'closed loop'
xs, ys = zip(*coord)    # create lists of x and y values

plt.figure()
plt.plot(xs, ys)
plt.fill(xs, ys, color="r")
plt.gca().set_aspect('equal') # needed so squares look square, x and y axis get the same pixels per unit
plt.show()

显示一个漂亮的正方形: 绘制的正方形 PS:上面的版本将坐标存储为字符串,而直接使用数字可能更有效。

更好、更易读的版本(@ImportanceOfBeingErnest 建议):

import csv
from matplotlib import pyplot as plt

x = []
y = []
# coord = [[1,1], [2,1], [2,2], [1,2],]
with open('screen.txt', 'r') as csvfile:
    coord = csv.reader(csvfile, delimiter=',')
    for row in coord:
        x.append(float(row[0]))
        y.append(float(row[1]))
x.append(x[0])
y.append(y[0])

plt.figure()
plt.plot(x, y)
plt.fill(x, y, color="orchid")
plt.show()

推荐阅读