擅长:python、mysql、java
<p>尝试遍历数组中的元素,如果字典中存在相同元素,则将其值增加1;如果不存在,则仅设置1。你知道吗</p>
<p>像这样:</p>
<pre><code># Hello World program in Python
import pprint
itemsSatchel = {'Arrow': 12,
'Gold Coin': 42,
'Rope': 1,
'Torch': 6,
'Dagger':1}
dragonLoot = ['Gold Coin',
'Gold Coin',
'Dagger',
'Gold Coin',
'Ruby']
def addToSatchel():
for item in dragonLoot:
if item in itemsSatchel:
itemsSatchel[item] += 1
else:
itemsSatchel[item] = 1
def displaySatchel():
print("Inventory: ")
itemsCounter = 0
for k,v in itemsSatchel.items() :
pprint.pprint(str(v) + ' ' + str(k))
itemsCounter += v
print('Total number of items: ' + str(itemsCounter))
addToSatchel()
displaySatchel()
</code></pre>
<p>干杯!你知道吗</p>