如何正确实现AlchemicalStorage类的按名称pop元素方法?
修正AlchemicalStorage的pop方法实现
你的现有pop逻辑完全偏离需求,以下是符合要求的实现:
def pop(self, element_name: str) -> AlchemicalElement | None: """ Remove and return previously added element from storage by its name. If there are multiple elements with the same name, remove only the one that was added most recently to the storage. If there are no elements with the given name, do not remove anything and return None. :param element_name: Name of the element to remove. :return: The removed AlchemicalElement object or None. """ # 从列表末尾向前遍历,优先匹配最近添加的元素 for idx in reversed(range(len(self.storage_list))): current_element = self.storage_list[idx] if current_element.name == element_name: return self.storage_list.pop(idx) # 无匹配元素时返回None return None
逻辑说明
- 采用反向遍历从列表最后一位(最新添加的元素)开始检查,确保找到的第一个匹配项就是最近添加的目标元素
- 找到匹配元素后,用
pop(idx)直接移除该位置的元素并返回,避免额外的列表操作 - 遍历结束未找到匹配项时,返回
None
验证测试
storage = AlchemicalStorage() element_one = AlchemicalElement('Fire') element_two = AlchemicalElement('Water') element_three = AlchemicalElement('Water') storage.add(element_one) storage.add(element_two) storage.add(element_three) print(storage.pop('Water') == element_three) # 输出 True print(storage.pop('Water') == element_two) # 输出 True print(storage.pop('Earth')) # 输出 None
内容的提问来源于stack exchange,提问作者fallguy
相关产品推荐
相关产品推荐

