擅长:python、mysql、java
<p>首先,使用工厂。开始于:</p>
<pre><code>def makecounter():
return collections.defaultdict(int)
</code></pre>
<p>以及以后使用</p>
^{pr2}$
<p>作为<code>for term in tokens:</code>循环</p>
<pre><code> for term in tokens:
self._inverted_index[term][docnumber] +=1
</code></pre>
<p>这将在每个<code>self._inverted_index[term]</code>中留下一个dict,例如</p>
<pre><code>{1:2,5:3,7:1}
</code></pre>
<p>在你的例子中。由于您希望在每个<code>self._inverted_index[term]</code>中包含一个列表列表,因此在循环结束后添加:</p>
<pre><code>self._inverted_index = dict((t,[d,v[d] for d in sorted(v)])
for t in self._inverted_index)
</code></pre>
<p>一旦制造出来(不管是这种方式还是其他方式,我只是展示一种简单的构建方法!),这个数据结构实际上会很难使用,因为您不必要地使其难以构建(当然,dict的dict更有用、更易于使用和构造),但是,嘿,一个人的男人肉&c;-)。在</p>