擅长:python、mysql、java
<p>您正在生成1到1000之间的9999个(有点)随机整数<em>,存储在<code>somedata</code>中,它用作<code>somehash</code>的键,用于存储某些数据中数字的出现。</p>
<p>作为<code>maxkey=0</code>,这个键将永远不存在。在使用defaultdict时,<em><a href="http://docs.python.org/release/2.5.2/lib/defaultdict-examples.html" rel="nofollow">when each key is encountered for the first time, an entry is automatically created using the ^{<cd4>} function which returns an empty list</a></em>,因此在迭代过程中正确地抛出了一个错误,正如*fasturtle*已经指出的那样。</p>
<p>使用<code>get</code>方法安全地检索项。</p>
<pre><code>import random
import collections
somedata=[random.randint(1,1000) for i in xrange(1,10000)]
somehash=collections.defaultdict(int)
for d in somedata:
somehash[d]+=1
maxkey=0
for k,v in somehash.iteritems():
if somehash.get(maxkey) > v:
maxkey=k
print k,v
</code></pre>
<hr/>
<p>我看到您正在使用Python 2.7,它有一个名为<code>Counter</code>的新集合类,用于计算散列对象。使用<code>Counter</code>应该比上面的代码快,并将代码缩减为:</p>
<pre><code>somedata=[random.randint(1,1000) for i in xrange(1,10000)]
somehash=collections.Counter(somedata)
</code></pre>