def getAvg(channel_id):
videos = v_db.find({'channelId':channel_id})
if len(list(videos)) > 1:
total_days=0
first = True
print('here-1')
for video in list(videos):
data = video['publishedAt']
print('here-2')
if first:
old_date = formatDate(data)
first = False
continue
else:
current_date = formatDate(data)
days = abs((old_date - current_date).days)
old_date = current_date
total_days += int(days)
avg = total_days / len(list(videos))
avg = round(avg, 0)
else:
avg = None
return avg
What’s the problem with this damn loop? I don’t understand why the method doesn’t acces the loop. I tried to make videos a list because cursor type can’t be parsed. If I’m running this for loop alone, without the if statement above, it works.
videos = v_db.find({'channelId':'UC8PQ5xjJNp6wgpF9GXmlkvw'})
for video in list(videos):
print('here-2')
Advertisement
Answer
videos is an iterable, and you can only iterate over it once. You exhaust it when you do if len(list(videos)) > 1:, so there’s nothing left when you try to do for video in list(videos):.
The solution is to put the list in a variable.
def getAvg(channel_id):
videos = list(v_db.find({'channelId':channel_id}))
if len(videos) > 0:
total_days=0
first = True
print('here-1')
for video in videos:
data = video['publishedAt']
print('here-2')
if first:
old_date = formatDate(data)
first = False
continue
else:
current_date = formatDate(data)
days = abs((old_date - current_date).days)
old_date = current_date
total_days += int(days)
avg = total_days / len(videos)
avg = round(avg, 0)
else:
avg = None
return avg
Also, you should test len > 0. There’s no problem with calculating the average of 1 video.