import csv
with open('scores.csv') as handle:
reader = csv.reader(handle)
for row in list(reader)[1:]:
user, *scores = row
average = sum([int(score) for score in scores]) / len(scores)
print (
"{user} has average of {average}".format(user=user,average=average)
)
由于*分数,此代码在python 2.7中不起作用。我如何将其更改为python 2.7,因为我不知道如何?
此代码取自此主题:Row Average CSV Python
答案 0 :(得分:5)
更改行
user, *scores = row
到
user, scores = row[0], row[1:]
除了上述内容外,您还应该更改
average = sum([int(score) for score in scores]) / len(scores)
到
average = sum([int(score) for score in scores]) / float(len(scores))
Python 2.X中的除法是整数除法。或者,您也可以从未来导入实际部门
from __future__ import division
并使用整数除法使用双正斜杠' //'
答案 1 :(得分:1)
你应该让我们的代码与python 3尽可能兼容,以及将来的导入:
from __future__ import division, print_function
import csv
with open('scores.csv') as handle:
reader = csv.reader(handle)
next(reader) # header
for row in reader:
user = row[0]
scores = row[1:]
average = sum(int(score) for score in scores) / len(scores)
print (
"{user} has average of {average}".format(user=user, average=average)
)