擅长:python、mysql、java
<p>你的代码几乎准确无误。您只需要看看如何在这两行中计算<code>final_list</code>之间的差异:</p>
<pre><code>final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']
</code></pre>
<p>还有。。。在</p>
^{pr2}$
<p>第一个是字符串列表,第二个是列表列表。第二个是正确的-CSV文件中的每一行都应该是一个列表。要更正代码,请将第一行(标题)也列为列表:</p>
<pre><code>import csv
# note that we have really only changed the next line
final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]
for key, value in sorted(stats_dict.iteritems()):
if value[5] != 0:
final_list.append([key, value[4], value[5], value[0], value[1]])
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(final_list) # we use writerows not writerow
</code></pre>