我似乎无法将我的比率显示在我正在编写的.txt文件中。我也无法将我的.txt文件分开。我在每个out.write语句的末尾添加了“\ n”,但不知道是否有其他方法。 .txt文件应为:
Russian Fed., 2.296, Well Above Average
Norway, 50.89, Well Above Average
Canada, 7.083, Well Above Average
//etc..
这里也是我引用上下文的csv http://www.cs.uni.edu/~diesburg/courses/cs1510_sp17/homework/PA06/medalData.csv
这是我的代码
import csv
medal=[]
av=[]
i=0
country=[]
out = open('results.txt','w')
with open('hw06.csv', 'r') as f:
reader = csv.reader(f,delimiter=',')
for row in reader:
if row[1]!='Country':
medal.append(int(row[3])+int(row[4])+int(row[5]))
country.append(row[1])
out.write(row[1])
average = round(((medal[i]/int(row[2])) * 10000000),3)
av.append(average)
if average < 0.672 :
out.write("WELL Below Average""\n")
elif average >= 0.672 and average <= 1.171:
out.write("Below Average""\n")
elif average == 1.172:
out.write("Average""\n")
elif average >= 1.173 and average <= 1.672 :
out.write("Above Average""\n")
elif average > 1.672:
out.write("WELL Above Average""\n")
i+=1
out.close()
Higest_loc =av.index(max(av))
lowest_loc =av.index(min(av))
print(country[Higest_loc],"has the Highest Ratio")
print(country[lowest_loc],"has the Lowest Ratio")
答案 0 :(得分:0)
我通过修改if..elif
结构中的write语句来实现它。以下是更新的代码
import csv
medal=[]
av=[]
i=0
country=[]
out = open('results.txt','w')
with open('medalData.csv', 'r') as f:
reader = csv.reader(f,delimiter=',')
for row in reader:
if row[1]!='Country':
medal.append(int(row[3])+int(row[4])+int(row[5]))
country.append(row[1])
out.write(row[1])
average = round(((medal[i]/int(row[2])) * 10000000),3)
av.append(average)
if average < 0.672 :
out.write(", {}, WELL Below Average""\n".format(average))
elif average >= 0.672 and average <= 1.171:
out.write(", {}, Below Average""\n".format(average))
elif average == 1.172:
out.write(", {}, Average""\n".format(average))
elif average >= 1.173 and average <= 1.672 :
out.write(", {}, Above Average""\n".format(average))
elif average > 1.672:
out.write(", {}, WELL Above Average""\n".format(average))
i+=1
out.close()
Higest_loc =av.index(max(av))
lowest_loc =av.index(min(av))
print(country[Higest_loc],"has the Highest Ratio")
print(country[lowest_loc],"has the Lowest Ratio")