擅长:python、mysql、java
<p>使用<a href="https://docs.python.org/3/library/collections.html?highlight=defaultdict#collections.defaultdict" rel="nofollow">defaultdict</a>:</p>
<pre><code>from collections import defaultdict
call_times = defaultdict(int)
with open('phone.txt') as fobj:
for line in fobj:
number, call_time = line.split(';')
call_times[number.strip()] += int(call_time)
>>> call_times
defaultdict(int, {'7801234567': 2143, '7803214567': 94, '7808765432': 925})
</code></pre>
<p><code>defaultdict</code>允许指定一个可调用项,为丢失的键创建一个新值。例如,这个<code>defaultdict</code>:</p>
<pre><code>>>> call_times = defaultdict(int)
>>> call_times
defaultdict(int, {})
</code></pre>
<p>为它没有的键返回<code>0</code>:</p>
<pre><code>>>> call_times['a']
0
</code></pre>
<p>因为它使用<code>int()</code>作为这样的键:</p>
<pre><code>>>> int()
0
</code></pre>
<p>因此,您可以使用<code>+=</code>将数字相加:</p>
<pre><code>>>> defaultdict(int, {'a': 0})
>>> call_times['b'] += 1
>>> call_times
defaultdict(int, {'a': 0, 'b': 1})
</code></pre>