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

使用OpenPyXl合并Excel报告时如何生成含全部元素的有序主标签列表

多有序标签列表合并实现方案

实现思路

  • 统计每个标签在所有输入列表中的最大出现次数,保证重复标签(如你场景中的重复carrot表头)能完整保留
  • 按照所有标签在输入列表中首次出现的顺序确定全局排列顺序,完全符合你要求的原有顺序规则
  • 最后按全局顺序和最大出现次数生成最终合并列表

代码实现

from collections import defaultdict

def merge_label_lists(*all_lists):
    # 统计每个标签的最大出现次数
    max_count = defaultdict(int)
    for lst in all_lists:
        curr_count = defaultdict(int)
        for item in lst:
            curr_count[item] += 1
        for item, cnt in curr_count.items():
            max_count[item] = max(max_count[item], cnt)
    
    # 确定全局标签顺序(按首次出现先后排列)
    global_order = []
    seen = set()
    for lst in all_lists:
        for item in lst:
            if item not in seen:
                seen.add(item)
                global_order.append(item)
    
    # 生成最终合并列表
    merged = []
    for item in global_order:
        merged.extend([item] * max_count[item])
    return merged

# 测试用例
lst1 = ["zucchini","apple","banana","carrot","carrot","escarole"]
lst2 = ["apple","carrot","escarole","squash"]
lst3 = ["zucchini","apple","escarole","squash"]

lst4 = merge_label_lists(lst1, lst2, lst3)
print(lst4)

输出结果

运行上述代码得到的lst4完全符合你的预期:
["zucchini","apple","banana","carrot","carrot","escarole","squash"]

你后续可以直接用这个主列表作为基准,对齐每个报告的标签行,不会出现数值错位的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:15:03