如何从Python字典列表中基于type键删除指定单个字典条目
需求实现解答
该需求完全可以实现,两种实现思路可选,你可以根据业务场景选择提前删除指定条目,或者在筛选可用人员时直接添加排除条件。
方案1:提前删除指定人员条目(后续所有统计都生效)
你可以单独封装一个按名称删除员工的工具函数,调用后得到的新员工列表就不会包含目标人员,后续所有统计逻辑都不会再纳入该条目。
示例代码如下:
def remove_employee_by_name(employees, target_name): # 列表推导式过滤掉目标姓名的条目,返回新列表不会影响原数据 return [emp for emp in employees if emp.get('name') != target_name] # 调用示例:删除Pippin filtered_employees = remove_employee_by_name(employees, 'Pippin') # 此时再筛选Uncertified Installer,就只会返回Frodo uncertified_installers = [emp for emp in filtered_employees if emp.get('type') == 'Uncertified Installer'] print(uncertified_installers) # 输出:[{'name': 'Frodo', 'type': 'Uncertified Installer', 'days_available': ['M', 'Tu', 'W', 'Th', 'F']}]
方案2:仅在筛选Uncertified Installer时临时排除
如果你不需要全局删除该人员,只是在筛选该类型人员时不纳入统计,可以直接在过滤条件里加排除规则。结合你现有schedule函数的修改示例如下:
def schedule(buildings, employees): # 注意:遍历列表时直接修改原列表会导致索引异常,这里遍历buildings的副本 for building in buildings.copy(): remaining_employee_list = employees.copy() if building == 'single': # 过滤规则新增排除name为Pippin的条目 remaining_employee_list[:] = [d for d in employees if (d.get('type')!='Handyperson') and (d.get('type')!='Uncertified Installer') and d.get('name') != 'Pippin'] buildings.remove('single') print(building, remaining_employee_list)
注意事项
你现有代码中remaining_employee_list=employees.copy()是浅拷贝,如果你后续需要修改员工字典内部的字段(比如修改可用日期),会同步影响原employees列表里的对应条目,如果要完全隔离数据,可以用copy模块的deepcopy方法。
内容的提问来源于stack exchange,提问作者Graham Oxman
相关产品推荐
相关产品推荐

