简体   繁体   English

从 Python 中的列表中删除重复项

[英]Removing duplicates from list in Python

I'm new to programming and I'm really stuck on trying to remove a certain amount of duplicates from a list.我是编程新手,我真的很想从列表中删除一定数量的重复项。

I'm making a text based game and I'm trying to set up a shop where you can sell items.我正在制作基于文本的游戏,并且正在尝试建立一个可以出售物品的商店。

If a player has, for example, 3 swords in his inventory and wants to sell 2 of them, keeping 1 of them in his inventory, I'm not sure how to implement this in to my code.例如,如果一个玩家在他的库存中有 3 把剑,并且想要出售其中的 2 把,将其中 1 留在他的库存中,我不知道如何在我的代码中实现这一点。

Example code:示例代码:

option refers to the item they're selling eg 'sword'.选项是指他们出售的物品,例如“剑”。 valitems is a dictionary of various items in the game. valitems 是游戏中各种物品的字典。

option4 = input('Enter selling quantity: ')
if option4 <= PlayerIG.inventory.count(option):
                    PlayerIG.inventory -= option4 * [option]
                    PlayerIG.gold += valitems[option]['SPrice']

I know this isn't working, however using "PlayerIG.inventory += option4 * [option]" got my buying side of the store system to work properly, but for some reason using the same code but for removing from the inventory, it does not seem to work.我知道这不起作用,但是使用“PlayerIG.inventory += option4 * [option]”让我的商店系统的买方正常工作,但由于某种原因使用相同的代码但从库存中删除,它似乎不起作用。

You can do this by using the list.remove method.您可以使用list.remove方法来做到这一点。 It deletes the first instance of the value you pass, so you will have to do this option4 number of times.它会删除您传递的值的第一个实例,因此您必须执行此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']

You could use a defaultdict from the collections module to manage your inventory.您可以使用collections模块中的defaultdict来管理您的库存。

from collections import defaultdict

# create a default dict with 0 as the default value
inventory = defaultdict(int)

You can add or remove items to/from the inventory as follows:您可以按如下方式在库存中添加或删除项目:

# 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

Bear in mind that option and item need to be hashable for this to work.请记住, optionitem需要是可散列的才能工作。 If they are strings, they are hashable.如果它们是字符串,它们是可散列的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM