擅长:python、mysql、java
<p>Stephan202有正确的答案,使用<code>defaultdict</code>。但是如果你想用C++的STL多功能接口和更糟糕的性能来做一些事情,你可以这样做:</P>
<pre><code>multimap = []
multimap.append( (3,'a') )
multimap.append( (2,'x') )
multimap.append( (3,'b') )
multimap.sort()
</code></pre>
<p>现在,当您遍历<code>multimap</code>时,将得到与在<code>std::multimap</code>中一样的对。不幸的是,这意味着你的循环代码会变得和C++一样丑陋。</p>
<pre><code>def multimap_iter(multimap,minkey,maxkey=None):
maxkey = minkey if (maxkey is None) else maxkey
for k,v in multimap:
if k<minkey: continue
if k>maxkey: break
yield k,v
# this will print 'a','b'
for k,v in multimap_iter(multimap,3,3):
print v
</code></pre>
<p>总之,<code>defaultdict</code>非常酷,利用了python的强大功能,您应该使用它。</p>