擅长:python、mysql、java
<h3>获取计数</h3>
<p>我认为问题的根源在于你把“数”和“总数”区分开来。“count”<em>是该项的出现总数。另外,你误用了<code>collections.Counter()</code>,它可以使你的工作变得更容易。下面是一个代码示例,说明我认为您正在努力实现的目标:</p>
<pre><code>counts = collections.Counter(line[1] for line in reader if len(line) > 1)
#Now all the occurrences of each item are summed up, AND ordered by number of occurrences
print "Total number of animals: %d" % len(counts)
#This is what I THINK you are trying to do.
</code></pre>
<p>另外:</p>
<pre><code>for name, number in counts.items():
print "# of %s: %d" % (name, number)
</code></pre>
<h3>关于你的“TypeError”:</h3>
<p>你有一个字符串列表,而不是整数列表。</p>
<p>例如:</p>
<pre><code>mylist = ['1', '2', '3']
</code></pre>
<p>所有的<code>sum()</code>都是对iterable执行累积加法,类似于:</p>
<pre><code>total = 0
for item in mylist:
total = total + item
</code></pre>
<p>在本例中,<code>total</code>是一个<code>int</code>(值0),而<code>item</code>是一个<code>str</code>(值“1”)。Python不知道如何处理<code>0 + 'string'</code>。</p>