擅长:python、mysql、java
<p>不要用列表,用字典代替。将人名存储为键,将累计和存储为值。你知道吗</p>
<pre><code>names_in_file = {}
with open("Pencils.txt","r") as file:
for line in file:
pencil_list = line.split(",")
names_in_file[pencil_list[0]] = names_in_file.get(pencil_list[0], 0) + int(pencil_list[1])
</code></pre>
<p>然后,在读取完文件之后,通过在已形成的字典中处理键和值来形成输出文件。你知道吗</p>
<pre><code>out_content = ''
for name, age in names_in_file.iteritems():
out_content = '{}{}\t{}\n'.format(out_content, name, age)
with out_file as open('path_to_out_file', "wt"):
out_file.write(out_content)
</code></pre>
<p><strong>注意</strong>:我用更多python名称重命名了变量。你知道吗</p>
<p><strong>祝你好运:)!</strong></p>