Python车辆买卖程序属性筛选结果与输入不匹配问题求助
问题产生原因
- 核心原因是遍历列表的同时直接删除列表元素,导致列表动态收缩后索引错位,跳过了下一个待检查的元素:比如初始列表索引0是蓝色丰田、1是红色本田、2是黑色道奇、3是红色雅马哈,筛选蓝色时,检查索引0符合条件不删除,接下来检查索引1的红色本田删除,删除后原索引2的道奇自动变成索引1,下一轮循环直接到索引2(原雅马哈),直接跳过了道奇的检查,所以不符合条件的道奇被留在了列表里。
- 其次价格筛选还存在两个额外问题:
- 价格范围判断的边界逻辑有误:你当前的逻辑是
<=low或>=high就删除,意味着等于边界值的车辆会被误删,正常应该是<low或>high时才删除,保留[low, high]区间的车辆。 options函数中调用price方法时存在语法错误:你写的if showcase.price(b) > showcase.price(c)只传了1个参数,但price方法要求传入low和high两个参数,运行时会直接报错。- 你在
price方法中调用的清空重置方法是小写self.reset(),但类中定义的重置方法是大写开头的Reset,会触发属性不存在报错。
- 价格范围判断的边界逻辑有误:你当前的逻辑是
修复方案
1. 修正所有筛选方法的遍历逻辑,用列表推导式生成新的筛选后列表,避免边遍历边删元素
把year、color、price三个筛选方法都改成如下写法:
# 按年份筛选 def year(self, year): target_year = int(year) # 直接生成符合条件的新列表替换原preferences self.preferences = [car for car in self.preferences if int(car.getYear()) == target_year] if not self.preferences: print("There are no cars from this year") self.Reset() print(self.preferences) # 按颜色筛选 def color(self, color): target_color = str(color) self.preferences = [car for car in self.preferences if str(car.getColor()) == target_color] if not self.preferences: print("There are no cars of this color") self.Reset() print(self.preferences) # 按价格区间筛选 def price(self, low, high): low_price = int(low) high_price = int(high) # 修正边界逻辑,保留[low, high]区间的车辆 self.preferences = [car for car in self.preferences if low_price <= int(car.getPrice()) <= high_price] if not self.preferences: print("There are no cars from this price range") self.Reset()
2. 修正options函数中价格筛选的错误调用
把原来的价格筛选分支:
elif int(a) == 2: b = input("Pick a lower price range: ") c = input("Pick an upper price range: ") if showcase.price(b) > showcase.price(c): print("Invalid Error") else: showcase.price(b,c)
改成:
elif int(a) == 2: b = input("Pick a lower price range: ") c = input("Pick an upper price range: ") low = int(b) high = int(c) if low > high: print("Invalid Error: Lower price cannot be higher than upper price") else: showcase.price(b,c)
修改完成后所有筛选逻辑即可正常运行。
内容的提问来源于stack exchange,提问作者Peter Joseph Williams
相关产品推荐
相关产品推荐

