-1
此算法只能在具有四個元素的列表中使用csv文件。我的算法需要在Python中處理不同數量的csv輸入/輸出元素
但是,我不知道如何csv文件得到多於或少於4個元素的算法。我嘗試了很多方法,看了所有的網頁,但仍然沒有答案。
infilename = input("Enter the location of your input file : ")
outfilename = input("Enter the location of your input file : ")
infile = open(infilename, "r")
outfile = open(outfilename, "w")
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()
將try-except語句中的「if line」中的所有代碼括起來。我會幫你的。 –