python - 填充多边形,列表超出范围
问题描述
我正在尝试从 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()
解决方案
问题中的代码假设文件“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()
推荐阅读
- pandas - 如何将我的文本文件转换为 netcdf 文件。我有 1980 年至 2018 年间仅一个气象站的观测数据集
- rsync - rsync 到本地 USB 磁盘给出“rsync 错误 2(协议不兼容)
- c# - 如何在单个文件中包含另一个项目库和几个其他 .NET 库?
- php - PHP:如何正确发出获取请求?
- vuetify.js - Vuetify - v-simple-checkbox 防止 v-data-table row.click 事件
- node.js - 我已经使用加密模块加密了 node.js 中的数据,如何使用 crypto-js 在 react.js 中解密
- wordpress - ERR_EMPTY_RESPONSE 网站未使用 WP Bakery Page builder 和 Donare Store Theme 进行更新
- github - VS-Code 到 GitHub-Codespace // 代理问题
- postgresql - LSN 外部表示
- google-cloud-platform - 我找不到从 Google Cloud Platform 下载的 VM 登录凭据