1
inv = {'arrow': 12, 'gold coin': 42, 'rope': 1, 'torch': 6, 'dagger': 1}
def show_inv():
print('inventory:')
item_total = 0
for k, v in inv.items():
print(str(v)+ ' ' + (k))
item_total = item_total + v
print('total number of items: ' + str(item_total))
show_inv()
結果(如預期):
庫存:
12箭頭
42金幣
1繩
6火炬
1匕首
總項目數:62
但如何
item_total = item_total + v
給我正確的總價值?
編輯:爲什麼print(str(v))總是給我'匕首'鍵的價值?
這只是將字典的值加在一起給你的總數。 – Li357
每次迭代,它將當前項目的數量加到項目'item_total + v'的運行總數中,然後將該更新值存回'item_total = ...' – Aaron
如果你對' item_total'被分配給'item_total + v' - 分配發生之前,首先評估賦值的右側,所以一切都按照你的意圖工作。 – birryree