修复数组元素索引赋值异常问题,实现缺失值排查与DB重复检测
问题修复与功能实现
1. 核心问题修复:解决循环中断问题
原代码的关键问题是把整个for循环包裹在try-except块中,一旦某个元素在DB中找不到,就会触发ValueError并直接跳出循环,导致后续元素完全没机会处理。正确的做法是将try-except移到循环内部,逐个处理每个元素:
DB = ['a','b','g','f','g'] name = ['a','e','b','p'] wanted_columns = [-2 for _ in range(len(name))] missing_names = [] for i in range(len(name)): try: wanted_columns[i] = DB.index(name[i]) except ValueError: # 找不到的元素保留初始值-2,同时记录该元素 missing_names.append(name[i]) print(wanted_columns)
运行这段代码就能得到期望的输出:[0, -2, 1, -2]。
2. 输出name中不在DB的元素
上面的代码已经通过missing_names列表收集了所有不在DB中的元素,直接格式化输出即可:
if missing_names: print(f"The following is a list of name not present in the DB array: {','.join(missing_names)}")
3. 检测DB中的重复值
通过遍历DB并记录已出现的元素,找出重复项:
seen = set() duplicates = set() for item in DB: if item in seen: duplicates.add(item) seen.add(item) if duplicates: print(f"The calculation has been aborted, there is a duplicate DB: {','.join(duplicates)}")
完整整合代码
把所有功能合并后的完整代码:
DB = ['a','b','g','f','g'] name = ['a','e','b','p'] wanted_columns = [-2 for _ in range(len(name))] missing_names = [] # 逐个匹配name元素在DB中的索引 for i in range(len(name)): try: wanted_columns[i] = DB.index(name[i]) except ValueError: missing_names.append(name[i]) # 输出索引结果列表 print(wanted_columns) # 输出不在DB中的name元素 if missing_names: print(f"The following is a list of name not present in the DB array: {','.join(missing_names)}") # 检测并输出DB中的重复元素 seen = set() duplicates = set() for item in DB: if item in seen: duplicates.add(item) seen.add(item) if duplicates: print(f"The calculation has been aborted, there is a duplicate DB: {','.join(duplicates)}")
运行结果:
[0, -2, 1, -2] The following is a list of name not present in the DB array: e,p The calculation has been aborted, there is a duplicate DB: g
内容的提问来源于stack exchange,提问作者HoneyWeGOTissues
相关产品推荐
相关产品推荐

