querytimes = "SELECT video_id, COUNT(src_ip) FROM video GROUP BY video_id ORDER BY COUNT(src_ip) DESC"
cur.execute (querytimes)
dltimes = cur.fetchall()
for row in dltimes:
videoid = str(row [0])
downloadtimes = int(str(row [1]))
x.append(rank)
rank = rank + 1
y.append(downloadtimes)
v.append(videoid)
counter = dict(zip(v, y))
for n in xrange(1, max(counter.itervalues()) + 1):
perc = 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
if perc:
print '%.f%% videos have been downloaded %d times' % (perc, n)
这是我的代码。起初我从数据库中读取数据,然后将videoid和下载时间放入字典中,并进行一些计算,但是我得到了以下错误:
perc = 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
ZeroDivisionError: float division
有人可以帮忙吗?
答案 0 :(得分:3)
您是否检查过您的counter
字典至少有一个与nb == n
条件匹配的值?对我来说,似乎是您的sum
或len
返回0
...
检查出来:
>>> n = 3
>>> counter = {'a': 1}
>>> 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
>>> counter = {'a': 3}
>>> 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
100.0
答案 1 :(得分:0)
检查counter
是否为空 - 换句话说,如果dltimes
中返回的值没有元素。我会在for
循环中执行类似的操作:
if counter:
perc = 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter)
else:
perc = 0
或者,可能没有值nb == n
为真的值。在那种情况下:
s = sum(1 for nb in counter.itervalues() if nb == n)
if counter and s:
perc = 100. / s / len(counter)
else:
perc = 0