遍历nested dictionary值并按值为各客户生成设施排序有序列表
实现步骤
你可以按照先聚合客户、再按对应成本排序的逻辑实现,完整代码如下:
# 示例嵌套字典 transportation_cost = { 'Fac-1': {"Apple":4,"Samsung":5,"Huawei":6,"Nokia":8,"Motorolla":10}, 'Fac-2': {"Apple":6,"Samsung":4,"Huawei":3,"Nokia":5,"Motorolla":8}, 'Fac-3': {"Apple":9,"Samsung":7,"Huawei":4,"Nokia":3,"Motorolla":4}, 'Fac-4': {"Apple":3,"Samsung":4,"Huawei":8,"Nokia":4,"Motorolla":4}, 'Fac-5': {"Apple":4,"Samsung":7,"Huawei":5,"Nokia":3,"Motorolla":2} } # 收集所有唯一的客户名称 all_customers = set() for facility_cost in transportation_cost.values(): all_customers.update(facility_cost.keys()) # 生成排序后的结果字典 sorted_fac_per_customer = {} for customer in all_customers: # 构造(成本,设施名)元组列表,用于排序 cost_fac_pairs = [] for fac_name, cost_map in transportation_cost.items(): if customer in cost_map: cost_fac_pairs.append((cost_map[customer], fac_name)) # 按运输成本升序排序,成本相同时默认按设施名字符串顺序排序 cost_fac_pairs.sort() # 提取排序后的设施名列表,如果需要统一设施名大写,可将pair[1]改为pair[1].upper() sorted_fac_per_customer[customer] = [pair[1] for pair in cost_fac_pairs] # 打印输出结果 for customer, fac_list in sorted_fac_per_customer.items(): print(f'"{customer}" = {fac_list}')
输出结果
"Apple" = ['Fac-4', 'Fac-1', 'Fac-5', 'Fac-2', 'Fac-3'] "Samsung" = ['Fac-2', 'Fac-4', 'Fac-1', 'Fac-3', 'Fac-5'] "Huawei" = ['Fac-2', 'Fac-3', 'Fac-5', 'Fac-1', 'Fac-4'] "Nokia" = ['Fac-3', 'Fac-5', 'Fac-2', 'Fac-4', 'Fac-1'] "Motorolla" = ['Fac-5', 'Fac-3', 'Fac-4', 'Fac-2', 'Fac-1']
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

