Python如何将嵌套列表中的数值替换为字典指定的对应名称
解决方案
你当前的字典存储的是名称:索引的映射,要实现索引转名称,首先需要把字典反转,再遍历嵌套列表做替换即可。
步骤1:反转映射字典
生成索引:名称的映射字典,方便直接通过索引查询对应餐厅名:
# 反转原有字典 index_to_name = {v: k for k, v in restaurants_dict.items()}
步骤2:替换嵌套列表的索引为餐厅名
用嵌套列表推导式遍历所有子列表的索引,批量替换:
list_of_restaurants = [[index_to_name[idx] for idx in sublist] for sublist in list_of_restaurants_index]
如果担心存在字典里没有的异常索引,可以加兜底逻辑避免报错:
list_of_restaurants = [[index_to_name.get(idx, "未知餐厅") for idx in sublist] for sublist in list_of_restaurants_index]
原有代码优化建议
你当前生成list_of_restaurants_index的代码存在性能问题,每次调用list.index()都会遍历整列表,100个元素的场景下可以直接简化为如下写法,效率提升非常明显:
# 初始化100个空列表 list_of_restaurants_index = [[] for _ in range(100)] # 直接按索引填充值,无需循环判断 for ind, ind2 in out: list_of_restaurants_index[ind].append(ind2)
内容的提问来源于stack exchange,提问作者V2P
相关产品推荐
相关产品推荐

