你有一个CSV文件的个人歌曲评级,你想知道平均评级的一首歌。该文件将包含一首歌每行1-5的评级。在
编写一个名为average_rating
的函数,它接受两个字符串作为参数,其中第一个字符串表示包含歌曲分级的CSV文件的名称,格式为:“YouTubeID,artist,title,rating”,第二个参数是歌曲的YouTubeID。YouTubeID、artist和title都是字符串,而评级是1-5范围内的整数。此函数应返回输入YouTubeID的歌曲的平均评分。在
请注意,CSV文件的每一行都是来自用户的单独评分,而且每首歌可能会被多次评分。当你通读这个文件时,你需要追踪所有收视率的总和以及这首歌被评了多少次才能计算出平均收视率。(我的代码如下)
import csv
def average_rating(csvfile, ID):
with open(csvfile) as f:
file = csv.reader(f)
total = 0
total1 = 0
total2 = 0
for rows in file:
for items in ID:
if rows[0] == items[0]:
total = total + int(rows[3])
for ratings in total:
total1 = total1 + int(ratings)
total2 = total2 + 1
return total1 / total2
输入错误['评级.csv','rh5ta6ihqq']:除以零。我该如何解决这个问题?在
您可以使用pandas DataFrame来实现这一点。在
有一些令人困惑的事情,我认为重命名变量和重构将是一个明智的决定。如果一个函数负责获取某个特定
youtube id
的所有行,而另一个函数则用于计算平均值,这甚至会使事情变得更加明显。在相关问题 更多 >
编程相关推荐