[英]How to iterate over multiple dictionary key list(value) pairs
So, I'm trying to create a game.所以,我正在尝试创建一个游戏。 In this mechanic of the game the user is trying to use an item from the dictionary.
在这种游戏机制中,用户尝试使用字典中的项目。
inventory = {
"Health": ["Potion", "Hi-Potion","Elixer"],
"Weapons": ["Blade","Dagger","Staff"],
"Items": ["Glass", "Paper","Notes"],
"Components": ["Rusty Trombone"],
}
# Add and Use item
def add_to_inventory(item_type, item_name):
inventory[item_type].append(item_name)
def use_item():
for item_type, item_name in inventory.items():
print(item_type.title(),":",item_name)
use_item = input("What will you use? \n").title()
if use_item in inventory["Health"]:
position = inventory["Health"].index(use_item)
print(f"You've used {use_item}. {use_item} will now be discarded.")
return inventory["Health"].pop(position)
elif use_item in inventory["Weapons"]:
position = inventory["Weapons"].index(use_item)
print(f"You've used {use_item}. {use_item} will now be discarded.")
return inventory["Weapons"].pop(position)
elif use_item in inventory["Items"]:
position = inventory["Items"].index(use_item)
print(f"You've used {use_item}. {use_item} will now be discarded.")
return inventory["Items"].pop(position)
elif use_item in inventory["Components"]:
position = inventory["Compoents"].index(use_item)
print(f"You've used {use_item}. {use_item} will now be discarded.")
return inventory["Components"].pop(position)
use_item()
There's much redundancy, but I'm having trouble finding how to shorten my code.有很多冗余,但我很难找到如何缩短我的代码。
With the use_item function I want to first have the entire inventory on view for the user to make choosing what to use easier.对于 use_item function,我想首先让用户看到整个库存,以便更轻松地选择要使用的内容。 Then is the prompt to use the item.
然后是使用物品的提示。 I want to keep the title method for all strings in future cases where multiple word items would need it's first letter capitalized.
我想保留所有字符串的 title 方法,以防将来多个单词项目需要将首字母大写。 Using the position variable allows me to obtain the indexed position of the item being used.
使用 position 变量可以让我获得正在使用的项目的索引 position。 This allows me to use the pop method to not only discard the item from the inventory, but to return that item for its intended use (A key to open a door, using a weapon, recovering health, tinkering).
这使我可以使用 pop 方法不仅从库存中丢弃物品,而且还可以将该物品归还给它的预期用途(开门的钥匙、使用武器、恢复健康、修补)。
All mechanics haven't been coded yet, but the more I look at this portion the more I feel it can be done much better.尚未对所有机制进行编码,但我越看这部分就越觉得它可以做得更好。 I'm stumped on how to though.
我对如何去做感到困惑。
I was considering iterating through each key value pair, then discarding the item from the dictionary.我正在考虑遍历每个键值对,然后从字典中丢弃该项目。 But, I need the pop method to return the item in question (and end the function).
但是,我需要 pop 方法来返回有问题的项目(并结束函数)。 I ran into trouble from the key having a list value.
我遇到了具有列表值的键的麻烦。 The value being a list makes it easier to navigate through, but also presents the issue of needing further iteration - maybe with a nested for loop?
作为列表的值使其更容易浏览,但也提出了需要进一步迭代的问题——可能使用嵌套的 for 循环? But then I'm not sure how to implement that to work for this situation.
但是后来我不确定如何实现它以适应这种情况。
Since you're doing the same thing for each key in the dictionary, you could use a for
loop instead:由于您对字典中的每个键执行相同的操作,因此您可以改用
for
循环:
for key in inventory:
if use_item in inventory[key]:
position = inventory[key].index(use_item)
print(f"You've used {use_item}. {use_item} will now be discarded.")
return inventory[key].pop(position)
As you are repeating the same action multiple times, you could move it to a function in a for
loop.当您多次重复相同的操作时,您可以在
for
循环中将其移动到 function。
.remove()
does the index
and pop
in one method .remove()
在一个方法中做index
和pop
def discard(user_item, inventory):
for k, v in inventory.items():
if user_item in v:
print(
f"You've used {user_item}. {user_item} will now be discarded.")
inventory[k].remove(user_item)
return user_item
def use_item():
for item_type, item_name in inventory.items():
# Join will join elements nicely
# Use an f string to easily edit string format
print(f"{item_type.title()}: {', '.join(item_name)}")
# Try not to name variables after your function name
user_item = input("What will you use? \n").title()
discard(user_item, inventory)
Other suggestions have been commented in其他建议已在评论中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.