クイックスタートPythonプログラミング実践プロジェクトのタイトル、証言して最適化するために歓迎!
あなたは楽しいビデオゲームを作成します。選手リスト項目のデータ構造モデリングのためのワードである
コード。キーは、項目のリストを説明する文字列であり、値がどのくらいの選手オブジェクトを表す、整数値である
製品を。例えば、辞書値{ 'ロープ':1、 'トーチ':6 '金貨':42 '短剣':1、 '矢印':12} プレイすることを意味
家がロープを有し、トーチ6、42金貨のように。
可能な項目の任意のリストを受け取り、以下の通りですdisplayInventory()という名前の関数を、書きます:
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
displayInventory(stuff)
結果:
Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62
辞書への機能一覧、楽しいアイテムのためのゲームのリストは、
列車の戦利品が表現文字列のようなリストを征服すると仮定:
dragonLoot = [「ゴールドCOIN」、「ダガー」、「ゴールドコイン」、「ゴールドコイン」、「ルビー」 ]
関数addToInventory在庫がする(在庫、addedItems)という名前のパラメータの書き込み
addedItems引数は、リストで、アイテムのプレイヤーのリストを表す辞書である(前の項目と同じ)
だけdragonLootのように。
addToInventory()関数は、アイテムの更新リストを表す辞書を返す必要があります。コラムことに注意してください
テーブルは、複数の同一の項目を含めることができます。あなたのコードは次のようになります。
def addToInventory(inventory, addedItems):
# your code goes here
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
新しいコード:
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
#displayInventory(stuff)
def addToInventory(inventory, addedItems):
# your code goes here
for i in addedItems:
if i in inventory.keys():
inventory[i] += 1
else:
inventory.setdefault(i,1)
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
結果:
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48