基于类变量的列表操作



抱歉,如果我解释错误或使用了错误的措辞,我的程序员词汇表不是最好的。如果有人理解我的问题,并有更好的方法来解释,请随时这样做。我有一个类似于这里的问题。我想从列表中删除出现在另一个列表中的项目。但是一个列表将具有引用变量"的字符串;name";在类对象中。

class sword:
name = 'swordName'
class bow:
name = 'bowName'
class axe:
name = 'axeName'
inventory = [sword, bow, sword, axe]
select = ['bowName', 'swordName']

我希望能够创建一个列表";selectedItems"其中类对象在基于"中的字符串的库存之外;选择";其等于";name";类对象的。如果";库存;以及";选择";两者都有副本。

输出:

>> inventory = [bow, axe]    
>> selectedItems = [bow, sword]

如果有更多的";name";s中存在对应的类对象;存货";,并且忽略"0"中的字符串;选择";没有对应的类对象。

例如,如果";库存;为CCD_ 1;选择";则结果是"CCD_;库存;是CCD_ 3;selectedItems"是CCD_ 4。

解释这一点的一个简单方法是,select将从库存中获取,但如果select不能从库存中获得,则不会发生任何事情。

您可以用神奇的方法__eq____hash__创建基类,这可以让您根据需要管理比较对象:

class BaseItem:
name = None
def __init__(self):
self.__name = self.name
def __eq__(self, other):
return self.__name == other
def __hash__(self):
return id(self.__name)
def __repr__(self):
return f"'{self.__name}'"

class Sword(BaseItem):
name = "swordName"

class Bow(BaseItem):
name = "bowName"

class Axe(BaseItem):
name = "axeName"

inventory = [Sword(), Bow()]
select = ["swordName", "bowName", "axeName", "swordName", "bowName"]
# casting lists into sets and getting difference between them
result = set(inventory) - set(select)
print(result)  # output {'swordName', 'bowName'}

eq-实际上这里没有使用,但我补充说,您可以将对象与字符串、列表等进行比较:

Sword() in ["swordName"] # true
Sword() in ["bowName"] # false
Sword() == "swordName" # true
Sword() == "bowName" # false

hash-需要比较两个对象,实际上它用于获取两个集合之间的差异

repr-这不是真正需要的方法,它只需要漂亮地显示对象

selectedItems = list()
# make a new list of the names of the objects in the inventory
# inventory and inventory names have the same index for the same item
inventory_names = [x.name for x in inventory]
for s in select:
if s in inventory_names:
index = inventory_names.index(s)
inventory_names.pop(index)
selectedItems.append(inventory.pop(index))

最新更新