Python停车场系统代码执行查看空车位功能时出现‘bool对象不可下标访问’错误求助
问题分析与修复方案
嘿,我看到你的问题了,这个'bool' object is not subscriptable错误的根源其实出在**选项5(加载数据)**的代码里,选项1只是触发了已经被破坏的变量状态而已。
错误原因拆解
当你选择选项5加载数据时,这段代码存在严重问题:
for x in range(6): if start[x] == 0: parking_slots = False # 这里把整个列表替换成了单个布尔值 else: parking_slots = True # 同样,直接覆盖了整个列表
原本parking_slots是一个包含6个布尔值的列表,但经过这段循环后,它会被直接赋值成单个True或False(最后一次循环的结果)。当你之后选择选项1时,尝试用parking_slots[slot]去访问列表元素,此时parking_slots已经是一个布尔对象,自然会抛出“不可下标访问”的错误。
修复方案
你需要逐个更新列表中的元素,而不是替换整个列表。把选项5的代码改成这样:
if choice == 5: file = open("cps.txt", "r").readlines() start = [float(x.strip("\n")) for x in file] for x in range(6): if start[x] == 0: parking_slots[x] = False # 更新列表的第x个元素 else: parking_slots[x] = True # 更新列表的第x个元素
额外优化建议
另外,选项1里的判断条件可以更贴合变量的语义:
# 原来的写法 if parking_slots[slot] == 0: # 更清晰的布尔判断写法 if not parking_slots[slot]:
因为parking_slots里存的是布尔值,直接用not判断空车位会更易读。我还顺便修正了选项2里的拼写错误token→taken,让提示更准确。
完整修复后的代码
import time parking_slots = [] start = [] for i in range(6): start.append(0) for i in range(6): parking_slots.append(False) while True: print("1.view empty\n2.add\n3.remove\n4.save\n5.load\n6.exit") choice = int(input()) if choice == 1: print("Empty slots are: ") for slot in range(6): if not parking_slots[slot]: # 优化后的布尔判断 print(slot, end=" - ") print("") if choice == 2: index = int(input("Enter the index of the slot: ")) if start[index] == 0: start[index] = int(time.time()) parking_slots[index] = True else: print("this slot is already taken, please choose another one") if choice == 3: index = int(input("Enter the index of the slot: ")) print("Your bill is", int(time.time()) - start[index]) parking_slots[index] = False start[index] = 0 if choice == 4: open("cps.txt", "w").write("") for i in start: open("cps.txt", "a").write(str(i) + "\n") if choice == 5: file = open("cps.txt", "r").readlines() start = [float(x.strip("\n")) for x in file] for x in range(6): if start[x] == 0: parking_slots[x] = False # 修复:更新列表元素而非替换整个列表 else: parking_slots[x] = True # 修复:更新列表元素而非替换整个列表 if choice == 6: break
内容的提问来源于stack exchange,提问作者SuperAmmar 1
相关产品推荐
相关产品推荐

