Python嵌套字典(模拟货架)元素检测与定位异常问题排查
货架模拟Python程序异常修复问题
问题背景
我是编程新手,需实现一款模拟货架的Python程序,核心需求:
- 检测物品是否存在于货架的仓位中
- 打印物品所在的货架、行及仓位位置
当前程序存在异常:输入不存在的物品时,会输出上一次找到的位置;尝试添加else语句重置位置变量为None后,输出变为None None None。
原代码
shelf1 = { 'row0' : { 'bin1': ['A1', 'A2', 'A3'], 'bin2': ['A4', 'A5', 'A6'], 'bin3': ['A7', 'A8', 'A9'] }, 'row1' : { 'bin1': ['A10'], 'bin2': ['A11', 'A12', 'A13'], 'bin3': ['A14', 'A15'] }, 'row2' : { 'bin1': ['A16', 'A17', 'A18'], 'bin2': ['A19'], 'bin3': ['A20', 'A21', 'A22'] }, 'row3' : { 'bin1': ['A23'], 'bin2': ['A24'], 'bin3': ['A25'] } } testShelf = [shelf1] strShelf = ['shelf1] # 语法错误:缺少闭合引号 while True: assm = input('what board are you looking for? ').upper() print(assm) for shelf in testShelf: shlfNum = testShelf.index(shelf) for i, j in shelf.items(): temp1 = i for k,l in j.items(): temp2 = k if assm in l: shlf = strShelf[shlfNum] row = temp1 bin = temp2 try: if shlf and row and bin is None: print('item does not exist') else: print(shlf, row, bin) except NameError: print('invalid board assembly. Please try again')
原运行输出
shelf1 row0 bin1 what board are you looking for? a2 A2 shelf1 row0 bin1 what board are you looking for? a5 A5 shelf1 row0 bin2 what board are you looking for? a90 A90 shelf1 row0 bin2
尝试的修改及问题
给判断添加else语句重置变量,但修改后无论物品是否存在,输出都是None None None:
if assm in l: shlf = strShelf[shlfNum] row = temp1 bin = temp2 else: shlf = None row = None bin = None
解决方案
关键问题分析
- 变量未初始化:每次查询循环前没有重置位置变量,导致未找到物品时保留上一次的结果;添加else后,遍历到不含目标物品的仓位时会反复重置变量,最终覆盖掉找到的结果。
- 语法错误:
strShelf = ['shelf1]缺少闭合引号,会导致运行报错。 - 判断逻辑错误:
if shlf and row and bin is None的逻辑完全错误,实际要判断的是三个变量是否都为None(即未找到物品)。
修正后的完整代码
shelf1 = { 'row0' : { 'bin1': ['A1', 'A2', 'A3'], 'bin2': ['A4', 'A5', 'A6'], 'bin3': ['A7', 'A8', 'A9'] }, 'row1' : { 'bin1': ['A10'], 'bin2': ['A11', 'A12', 'A13'], 'bin3': ['A14', 'A15'] }, 'row2' : { 'bin1': ['A16', 'A17', 'A18'], 'bin2': ['A19'], 'bin3': ['A20', 'A21', 'A22'] }, 'row3' : { 'bin1': ['A23'], 'bin2': ['A24'], 'bin3': ['A25'] } } testShelf = [shelf1] strShelf = ['shelf1'] # 修正语法错误:添加闭合引号 while True: assm = input('what board are you looking for? ').upper().strip() # 去除输入首尾空格 print(assm) # 每次查询前初始化位置变量为None shlf = None row = None bin_loc = None # 避免和内置函数bin重名 for shelf_idx, shelf in enumerate(testShelf): for row_name, bins in shelf.items(): for bin_name, items in bins.items(): if assm in items: shlf = strShelf[shelf_idx] row = row_name bin_loc = bin_name # 找到物品后直接跳出所有循环,无需继续遍历 break if bin_loc is not None: break if bin_loc is not None: break # 判断是否找到物品 if shlf and row and bin_loc: print(shlf, row, bin_loc) else: print('item does not exist')
修改说明
- 初始化变量:每次查询开始时将
shlf、row、bin_loc设为None,确保每次查询都是独立状态。 - 修正语法错误:给
strShelf里的shelf1添加闭合引号。 - 优化循环逻辑:使用
enumerate获取货架索引更高效,找到物品后通过break跳出所有循环,减少不必要的遍历。 - 修正变量名:将
bin改为bin_loc,避免和Python内置函数bin()重名。 - 优化输入处理:添加
.strip()去除输入首尾的空格,避免因输入空格导致匹配失败。 - 修正判断逻辑:直接判断三个变量是否都不为空,为空则输出物品不存在。
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

