擅长:python、mysql、java
<p>您忘记关闭<code>open()</code>,这是使用<code>with</code>块的众多原因之一。总之,我假设这是输入文件的样式:</p>
<blockquote>
<p>Clinton 3<br/>
Cruz 2 <br/>
Sanders 3<br/>
Trump 2<br/>
Dutter 1</p>
</blockquote>
<p>您希望输出为:</p>
<blockquote>
<p>Republican 2<br/>
Democratic 2<br/>
Independent 1</p>
</blockquote>
<p>如果这是不正确的,那么这个函数应该改变,以完全适合你想要的。你知道吗</p>
<pre><code>from collections import defaultdict
def getCandidates(infile):
parties = {1: "Independent", 2: "Republican", 3: "Democratic", 4: "Unknown"}
candidates = defaultdict(int)
with open(infile, "r") as fin:
for line in fin: # assuming only 2 columns and the last column is the number
candidates[parties[int(line.split()[-1])]] += 1
for party, count in candidates.items(): #.iteritems() in python 2.7
print("{} {}".format(party, count))
getCandidates("test.txt")
</code></pre>