擅长:python、mysql、java
<p>我想这就是你要找的。关键是只迭代新列表中的唯一项,并将其添加到现有字典中,或者在该项不存在时更新该项。在</p>
<pre><code>alist = ["Book", "Coin", "Book", "Book", "Computer", "Bag"]
inventory = {"Book":3, "Bag":2}
for item in list(set(alist)): #get the unique items by converting them to a set
if item in result:
inventory[item] += alist.count(item)
else:
inventory[item] = alist.count(item)
#inventory would now become {"Book":6, "Coin":1", "Bag":3", "Computer":1}
</code></pre>
<p>同时,使用Stefan的方法。
如果库存是一个计数器,你可以这样做</p>
^{pr2}$