Skip to main content
 首页 » 编程设计

python之索引错误超出范围python

2025年05月04日9zhwl

由于某些原因,我在尝试运行以下代码时遇到此错误

#!/usr/bin/python 
import matplotlib.pyplot as plt 
x = [] 
y = [] 
readFile = open('Out_0_0.txt','r') 
sepFile = readFile.read().split('\n') 
readFile.close() 
for plotPair in sepFile: 
    xandy = plotPair.split() 
    x.append(int(xandy[0])) 
    y.append(int(xandy[1])) 
print x 
print y 

当我删除 x.append 和 y.append 行并只放置一个 print 语句来打印出 xandy 中的内容时,它会打印出数组中的每对值。文本文件有这个

 1 2 
 3 4 
 5 6 
 7 8 

我想要它做的就是将第一列存储在 x 数组中,将第二列存储在 y 数组中

请您参考如下方法:

问题在于您如何读取文件。

这会起作用。

x = [] 
y = [] 
with open('test.txt','r') as data_file: 
    for plot_pair in data_file: 
        xandy = plot_pair.split() 
        x.append(int(xandy[0])) 
        y.append(int(xandy[1])) 
print(x) 
print(y)