JavaScript
x
24
24
1
def getAvg(channel_id):
2
videos = v_db.find({'channelId':channel_id})
3
if len(list(videos)) > 1:
4
total_days=0
5
first = True
6
print('here-1')
7
for video in list(videos):
8
data = video['publishedAt']
9
print('here-2')
10
if first:
11
old_date = formatDate(data)
12
first = False
13
continue
14
else:
15
current_date = formatDate(data)
16
days = abs((old_date - current_date).days)
17
old_date = current_date
18
total_days += int(days)
19
avg = total_days / len(list(videos))
20
avg = round(avg, 0)
21
else:
22
avg = None
23
return avg
24
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.
JavaScript
1
4
1
videos = v_db.find({'channelId':'UC8PQ5xjJNp6wgpF9GXmlkvw'})
2
for video in list(videos):
3
print('here-2')
4
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.
JavaScript
1
24
24
1
def getAvg(channel_id):
2
videos = list(v_db.find({'channelId':channel_id}))
3
if len(videos) > 0:
4
total_days=0
5
first = True
6
print('here-1')
7
for video in videos:
8
data = video['publishedAt']
9
print('here-2')
10
if first:
11
old_date = formatDate(data)
12
first = False
13
continue
14
else:
15
current_date = formatDate(data)
16
days = abs((old_date - current_date).days)
17
old_date = current_date
18
total_days += int(days)
19
avg = total_days / len(videos)
20
avg = round(avg, 0)
21
else:
22
avg = None
23
return avg
24
Also, you should test len > 0
. There’s no problem with calculating the average of 1 video.