如何在字典列表追加前校验指定字段,避免重复记录?
解决驾驶员记录重复校验问题
原代码缺少重复记录校验逻辑,直接将新记录追加到列表中,无法实现“存在Name、Age、Team、Car完全相同的记录则不添加”的要求。以下是修改后的完整代码,同时优化了输入合法性校验的健壮性:
driver_list = [] # 获取姓名输入 name = input("Enter player name : ").strip() # 循环获取合法的年龄输入 while True: try: age = int(input("Enter the age : ").strip()) break except ValueError: print("Input an integer") # 获取车队名称输入 team = input("Enter team name : ").strip() # 获取赛车名称输入 car = input("Enter name of the car : ").strip() # 循环获取合法的当前积分输入 while True: try: current_points = int(input("Enter the current points of the player : ").strip()) break except ValueError: print("Input an integer") driver_details = {"Name": name, "Age": age, "Team": team, "Car": car, "Current_points": current_points} # 检查是否存在重复记录(匹配Name、Age、Team、Car四个字段) record_exists = False for existing_driver in driver_list: if (existing_driver["Name"] == name and existing_driver["Age"] == age and existing_driver["Team"] == team and existing_driver["Car"] == car): record_exists = True break if record_exists: print("该记录已存在") else: driver_list.append(driver_details) print("记录已成功添加")
关键修改说明
- 重复校验逻辑:在追加记录前遍历已有列表,逐一对比
Name、Age、Team、Car四个字段,只要存在完全匹配的记录就标记为已存在,不再执行追加操作。 - 输入优化:将年龄和积分的输入改为循环校验,直到用户输入合法的整数,避免单次异常捕获后再次输入错误导致程序崩溃。
- 输入处理:对所有字符串输入添加
strip()方法,去除首尾空格,避免因空格差异导致的误判(比如用户输入" Lewis "和"Lewis"被误认为不同记录)。
内容的提问来源于stack exchange,提问作者Nethum
相关产品推荐
相关产品推荐

