我试图从文本文件中找到平均值。文本文件包含数字列,我想查找每列的平均值。我得到了以下错误: IndexError:列表索引超出范围
我使用的代码是:
import os
os.chdir(r"path of my file")
file_open = open("name of my file", "r")
file_write = open ("average.txt", "w")
line = file_open.readlines()
list_of_lines = []
length = len(list_of_lines[0])
total = 0
for i in line:
values = i.split('\t')
list_of_lines.append(values)
count = 0
for j in list_of_lines:
count +=1
for k in range(0,count):
print k
list_of_lines[k].remove('\n')
for o in range(0,count):
for p in range(0,length):
print list_of_lines[p][o]
number = int(list_of_lines[p][o])
total + number
average = total/count
print average
错误在行
length = len(list_of_lines[0])
如果我能提供更多信息,请告诉我。
答案 0 :(得分:0)
问题是你试图获取数组中某些内容的长度,而不是数组本身。
试试这个:
{{1}}
答案 1 :(得分:0)
你写了length = len(list_of_lines[0])
line_of_lines
在此行的正上方定义,作为包含0个项目的列表。因此,您无法选择第一项(索引号0),因为索引号0不存在。因此,它超出了范围。