擅长:python、mysql、java
<p>对此,您可能希望使用Python字典而不是列表。您可能想了解<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">dictionaries</a>,但这是如何使用一个实现它的:</p>
<pre><code>name_pencil_dict = {} # Create the dictionary
with open("Pencils.txt","r") as file:
for line in file:
pencilArr = line.split(",")
name = pencilArr[0]
num_pencils = pencilArr[1]
if name not in list(name_pencil_dict.keys):
# Name not found, create new dictionary entry, initialize num pencils to zero
name_pencil_dict[name] = 0
# Add the number of pencils to the name's dictionary value
name_pencil_dict[name] += num_pencils
</code></pre>