[英]Removing duplicates from list in Python
我是編程新手,我真的很想從列表中刪除一定數量的重復項。
我正在制作基於文本的游戲,並且正在嘗試建立一個可以出售物品的商店。
例如,如果一個玩家在他的庫存中有 3 把劍,並且想要出售其中的 2 把,將其中 1 留在他的庫存中,我不知道如何在我的代碼中實現這一點。
示例代碼:
選項是指他們出售的物品,例如“劍”。 valitems 是游戲中各種物品的字典。
option4 = input('Enter selling quantity: ')
if option4 <= PlayerIG.inventory.count(option):
PlayerIG.inventory -= option4 * [option]
PlayerIG.gold += valitems[option]['SPrice']
我知道這不起作用,但是使用“PlayerIG.inventory += option4 * [option]”讓我的商店系統的買方正常工作,但由於某種原因使用相同的代碼但從庫存中刪除,它似乎不起作用。
您可以使用list.remove
方法來做到這一點。 它會刪除您傳遞的值的第一個實例,因此您必須執行此option4
次。
if option4 <= PlayerIG.inventory.count(
# delete `option` from inventory `option4` number of times
[PlayerIG.inventory.remove(option) for i in range(option4)]
gold += valitems[option]['SPrice']
您可以使用collections
模塊中的defaultdict
來管理您的庫存。
from collections import defaultdict
# create a default dict with 0 as the default value
inventory = defaultdict(int)
您可以按如下方式在庫存中添加或刪除項目:
# add
inventory[item] += number_of_items
# remove
number_of_items = input('Enter selling quantity: ')
item = input('Enter item to sell: ')
if number_of_items <= inventory[item]:
inventory[item] -= number_of_items
請記住, option
和item
需要是可散列的才能工作。 如果它們是字符串,它們是可散列的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.