You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于动态优先级字典/列表去重复杂字典中的重复元素

解决方案

核心思路

  • 先把优先级定义(列表/字典)统一转换成权重字典,方便优先级比较:
    • 如果是列表:列表索引越靠前的通道优先级越高,权重设为len(列表) - 索引(比如["ct","ca"]对应的权重是{"ct":2, "ca":1})
    • 如果是字典:直接使用给定的数值作为权重,数值越大优先级越高
    • 未在优先级定义中的通道,权重默认设为0(最低优先级)
  • 遍历所有通道的有效键,用临时字典记录每个有效键当前优先级最高的条目
  • 最后将临时字典中的条目统一处理后存入结果列表

完整代码实现

grouped = {
    "ca": {"k_a": 32, "k_d": 34},
    "ct": {"p_a": 98, "k_d": 34},
    "cd": {"k_a": 32, "c_a": 12},
}
valid = ["k_a", "k_d", "p_a"]

def process(v):
    # 保留原有处理逻辑,示例直接返回原条目
    return v

def build_priority_weight(priority_def):
    """将优先级定义(列表/字典)转换为可比较的权重字典"""
    weight_dict = {}
    if isinstance(priority_def, list):
        # 列表形式:靠前的通道优先级更高,权重按倒序赋值
        for idx, channel in enumerate(priority_def):
            weight_dict[channel] = len(priority_def) - idx
    elif isinstance(priority_def, dict):
        # 字典形式:直接使用给定数值作为权重
        weight_dict.update(priority_def)
    # 未定义的通道默认权重为0(最低优先级)
    return weight_dict

# 优先级定义可动态切换,无需修改核心逻辑
priority = {"ca":3,"ct":1}  # 字典形式示例
# priority = ["ct","ca"]  # 列表形式示例

# 构建统一权重字典
priority_weights = build_priority_weight(priority)
# 临时存储每个有效键的最高优先级条目:key为有效键,value为(权重, 条目)
highest_priority_entries = {}

for channel, items in grouped.items():
    current_weight = priority_weights.get(channel, 0)
    for key, value in items.items():
        if key not in valid:
            continue
        # 若当前键无记录,或当前通道权重更高,则更新记录
        if key not in highest_priority_entries or current_weight > highest_priority_entries[key][0]:
            entry = {"key": key, "value": value, "channel": channel}
            highest_priority_entries[key] = (current_weight, entry)

# 处理最终保留的条目
processed = []
for _, entry in highest_priority_entries.values():
    processed.append(process(entry))

print(processed)

代码说明

  • build_priority_weight函数实现了优先级格式的统一转换,不管输入是列表还是字典,都能生成可直接用于比较的权重字典,完全适配优先级的动态变化
  • 遍历过程中仅保留每个有效键的最高优先级条目,从根源避免重复
  • 原有的process函数逻辑完全保留,无需修改即可对接新的处理流程

内容的提问来源于stack exchange,提问作者user3541631

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:12:40