ZeroDivisionError:python中的float division`

时间:2011-12-06 11:01:25

标签: python

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

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

您是否检查过您的counter字典至少有一个与nb == n条件匹配的值?对我来说,似乎是您的sumlen返回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