我需要找到每个数据行的参与率,然后找到参与率最高的视频节目。
dict youtube_usa_videos中的'row'由许多元素组成,其中每个元素的索引均已命名。当我尝试设置条件(如下所示)时,就会出现问题,因为在数据集中有一些视图为零,因此python给出了“被零除”错误消息。
参与率=否。评论数/否的观看次数
#code below
highest_EGR = 0
for row in youtube_usa_videos:
comments = row [8]
views = row [5]
title = row [1]
if views != 0:
EGR = comments / views
else:
EGR = 0
If EGR > highest_EGR:
highest_EGR = EGR
top_vid = title
您能帮我清理代码以便满足条件并打印出顶部视频标题及其参与率吗?
答案 0 :(得分:0)
下面的代码很好用。
考虑将If
替换为if
highest_EGR = 0
youtube_usa_videos = [['t1',12,45],['t2',34,12],['t3',2,123]]
TITLE_OFFSET = 0
VIEWS_OFFSET = 1
COMMENTS_OFFSET = 2
for row in youtube_usa_videos:
comments = row [COMMENTS_OFFSET]
views = row [VIEWS_OFFSET]
title = row [TITLE_OFFSET]
if views != 0:
EGR = comments / views
else:
EGR = 0
if EGR > highest_EGR:
highest_EGR = EGR
top_vid = title
print('highest_EGR: {}'.format(highest_EGR))
# or using max and lambda
max_egr = max(youtube_usa_videos,key=lambda vid:vid[COMMENTS_OFFSET] / vid[VIEWS_OFFSET] if vid[VIEWS_OFFSET] else 0)
print('video with max eger: {}'.format(max_egr))
输出
highest_EGR: 61.5
video with max eger: ['t3', 2, 123]
答案 1 :(得分:0)
highest_EGR = 0
在youtube_usa_videos中的行:
comments = row [8]
views = row [5]
title = row [1]
if int (views) > 0:
EGR = int (comments) / int (views)
if EGR > highest_EGR:
highest_EGR = EGR
top_vid = title
print (top_vid, highest_EGR)
好吧,我只是将'if views!= 0:'更改为'if views> 0:'并删除了'else:'