匹配字典中苹果与果园对象并修改对应属性的实现咨询
解决方法
首先修正你代码里的两处关键错误:
- Python里布尔值是大写的
False,不是小写的false apple_dict的定义不符合字典格式,应该是果园ID作为键,对应同果园的苹果列表作为值,原写法会触发语法报错
修正后的类定义和字典初始化代码:
class Apple: def __init__(self, apple_id, orchard_id): self.apple_id = apple_id self.orchard_id = orchard_id self.found = False # 修正为Python标准布尔值写法 class Orchard: def __init__(self, id): self.id = id self.picked_apples = [] # 修正后的apple_dict:键为果园ID,值为对应果园的苹果对象列表 apple_dict = { "1": [Apple(1,1), Apple(3,1)], "2": [Apple(5,2)], "3": [Apple(2,3), Apple(4,3), Apple(6,3), Apple(7,3)] } orchard_dict = { "1": Orchard(1), "2": Orchard(2), "3": Orchard(3) }
接下来实现苹果与果园的匹配逻辑,核心是利用字典键的快速定位特性,批量处理同果园的苹果:
# 遍历每个果园ID对应的苹果列表 for orchard_id, apples in apple_dict.items(): # 通过果园ID快速获取对应的果园对象 target_orchard = orchard_dict.get(orchard_id) if not target_orchard: continue # 若果园不存在,跳过当前批次 # 逐个处理苹果对象 for apple in apples: apple.found = True # 修改苹果的found属性为True target_orchard.picked_apples.append(apple) # 将苹果添加到对应果园的采摘列表
可以用以下代码验证结果:
# 打印每个果园的采摘苹果信息 for orchard_id, orchard in orchard_dict.items(): print(f"果园 {orchard_id} 的采摘苹果:") for apple in orchard.picked_apples: print(f" 苹果ID: {apple.apple_id}, found状态: {apple.found}")
运行后输出:
果园 1 的采摘苹果: 苹果ID: 1, found状态: True 苹果ID: 3, found状态: True 果园 2 的采摘苹果: 苹果ID: 5, found状态: True 果园 3 的采摘苹果: 苹果ID: 2, found状态: True 苹果ID: 4, found状态: True 苹果ID: 6, found状态: True 苹果ID: 7, found状态: True
关键说明
- 利用字典
items()遍历的时间复杂度为O(n)(n为苹果总数),效率远高于逐个对比苹果和果园 - 用
orchard_dict.get(orchard_id)避免果园ID不存在时的KeyError,提升代码健壮性 - Python中对象是引用传递,直接修改遍历到的苹果对象和果园对象,就是修改原字典中的实例本身
内容的提问来源于stack exchange,提问作者user19678327
相关产品推荐
相关产品推荐

