获得了一个仅包含2行数据的csv列表,需要查找并显示3个得分中每个得分的平均值。
name tribe id Score1 Score2 Score3 Score4
Aang Normad N321B 89 67 54 78
Gyatso Omaticay O111C 54 78 65 54
成功打印了Score1的平均值,但是Score2,3和4显示为0,不确定代码的哪一部分是错误的。感谢任何能指出正确方向的人
def display_element_average():
with open(filePath) as csvfile:
reader = csv.DictReader(csvfile)
air_average= sum(float(row["Air"]) for row in reader) /2
water_average= sum(float(row["Water"]) for row in reader) /2
earth_average= sum(float(row["Earth"]) for row in reader) /2
fire_average= sum(float(row["Fire"]) for row in reader) /2
print("==============================")
print("Display element average")
print("==============================")
print("{0:<6}{1:^8}{2:^7}{3:^7}".format("Air |","Water |","Earth |","Fire |"))
print("{0:^6}{1:^8}{2:^7}{3:^7}".format(air_average, water_average, earth_average, fire_average))
def menu():
print ("=================================================================")
print ("Welcome to Avatar Element System")
print ("=================================================================")
print ("1: Display element average")
print ("2: Display avatar top element")
print ("0: Exit")
choice= input ("Enter choice:")
if (choice == "1"):
display_element_average()
elif (choice =="2"):
display_avatar_top_elements()
elif (choice =="0"):
print ("=================================================================")
print ("Thank you for using Avatar Element System")
print ("=================================================================")
exit (0)
menu()
答案 0 :(得分:0)
第一个生成器表达式将读取器对象用尽,因此以下表达式无需重复。
您可以在for循环中累积值,然后在循环结束后计算平均值。
air, water, earth, fire = 0,0,0,0
with open(filePath) as csvfile:
reader = csv.DictReader(csvfile)
for count, row in enumerate(reader, 1):
air += float(row["Air"])
water += float(row["Water"])
earth += float(row["Earth"])
fire += float(row["Fire"])
fireave= fire / count
earthave = earth / count
waterave = water / count
airave = air / count