擅长:python、mysql、java
<p>您可以使用<a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">^{<cd1>}</a>使您的解决方案有效。使用<code>defaultdict</code>,可以指定键值对的值的默认类型。这允许您像<code>+=1</code>那样对尚未显式创建的键进行赋值:</p>
<pre><code>import codecs
from collections import defaultdict
def countTuples(path):
dic = defaultdict(int)
with codecs.open(path, 'r', 'utf-8') as f:
for line in f:
s = line.split()
for i in range (0, len(s)-1):
dic[str(s[i]) + ' ' + str(s[i+1])] += 1
return dic
>>> {'Once upon': 1,
'a time': 2,
'this upon': 1,
'time a': 1,
'time this': 1,
'upon a': 2})
</code></pre>