如何按字典内整数值之和对字典组合列表实现多条件排序
解决方案
基础排序(仅按整数总和降序)
你可以直接用Python内置的sorted()函数,自定义排序的key计算逻辑即可:
import itertools # 建议你把原代码中变量名list改掉,避免覆盖Python内置的list类型,这里假设改成data data = { "list1": [ {"name", "height", 10000000000}, {"name1", "height2", 90000000000} ], "list2": [ {"name", "height", 30000000000}, {"name1", "height2", 40000000000} ], "list3": [ {"name", "height", 50000000000}, {"name1", "height2", 60000000000} ] } keys = data.keys() values = (data[key] for key in keys) combinations = [dict(zip(keys, combination)) for combination in itertools.product(*values)] # 排序核心逻辑 def get_int_sum(comb): total = 0 # 遍历当前组合所有集合,累加所有整数 for item_set in comb.values(): for elem in item_set: if isinstance(elem, int): total += elem return total # 按总和降序排序 sorted_combinations = sorted(combinations, key=get_int_sum, reverse=True)
进阶排序(总和相等时按布尔值次优先级排序)
当集合中新增布尔值后,只需要把排序key改为元组即可,Python排序时会优先比较元组第一个元素,相等时自动比较后续元素:
def get_sort_key(comb): int_total = 0 # 统计所有为True的布尔值数量,可根据你的需求调整统计逻辑 true_count = 0 for item_set in comb.values(): for elem in item_set: if isinstance(elem, int): int_total += elem if isinstance(elem, bool): true_count += 1 if elem else 0 # 元组顺序对应排序优先级:先按整数总和,再按True的数量 return (int_total, true_count) # 按优先级降序排序,如果需要布尔值按升序排序,把true_count改为-true_count即可 sorted_combinations = sorted(combinations, key=get_sort_key, reverse=True)
内容的提问来源于stack exchange,提问作者Bob Linux
相关产品推荐
相关产品推荐

