我正在构建一个不使用模块的算法。 我的算法是从111.txt计算每行的值,其中
2,2,2,2
4,4,0,4
2,3,3,3
到222.txt。所以我想要的结果是
Column, Sum, Mean, STD, Median, Mode, Min, Max
1,8,2,0,2,2,2,2
2,12,3,2,4,4,0,4
3,11,2.75,0.5,3,3,2,3
我的算法是
infile = open("111.txt", "r")
outfile = open("222.txt", "w")
outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
for line in infile:
infileline = line.rstrip().split(",")
infileline.sort()
while line != "":
total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
mean = total / 4
std = ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
median = (float(infileline[1]) + float(infileline[2])) / 2
mode = 2
minimum = float(infileline[0])
maximum = float(infileline[3])
line = infile.readline()
outfile.write("1")
outfile.write(",")
outfile.write("%1.0f" % total)
outfile.write(",")
outfile.write("%1.0f" % mean)
outfile.write(",")
outfile.write("%1.0f" % std)
outfile.write(",")
outfile.write("%1.0f" % median)
outfile.write(",")
outfile.write("%1.0f" % mode)
outfile.write(",")
outfile.write("%1.0f" % minimum)
outfile.write(",")
outfile.write("%1.0f\n" % maximum)
infile.close()
outfile.close()
但问题是我的算法只读取111.txt上的第一行 因此,结果如下222.txt
Column,Sum,Mean,STD,Median,Mode,Min,Max
1,8,2,0,2,2,2,2
另外,我一直在思考,但我不知道如何编写列的算法和模式的算法。
答案 0 :(得分:0)
line = infile.readline()
。此代码必须如下所示:
infile = open("111.txt", "r")
outfile = open("222.txt", "a")
outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
column = 0
for line in infile:
if line:
column += 1
infileline = line.rstrip().split(",")
infileline.sort()
total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
mean = total / 4
std = ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
median = (float(infileline[1]) + float(infileline[2])) / 2
mode = 2
minimum = float(infileline[0])
maximum = float(infileline[3])
outfile.write(str(column)+',')
outfile.write(','.join("%1.0f"%i for i in (total, mean, std, median,
mode, minimum, maximum)))
outfile.write('\n')
infile.close()
outfile.close()