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

如何在tuple列表中合并同一debitor-name对应的多entity-ID?

解决方案:合并同一债务人对应的多实体ID

要实现将同一债务人名称对应的不同实体ID合并为列表的需求,可以通过字典分组的方式完成,具体步骤如下:

核心思路

  1. 用字典的键存储债务人名称,值存储对应实体ID的集合(或列表),自动去重同一债务人下重复的实体ID。
  2. 遍历原始元组列表,将每个实体ID归类到对应债务人的集合中。
  3. 最后将字典转换为目标格式的元组列表:([实体ID列表], 债务人名称)。

代码实现

方式1:用集合自动去重(推荐,效率更高)

# 初始化分组字典
debitor_map = {}
for entity_id, debitor_name in debitor_list:
    # 若债务人未在字典中,初始化空集合
    if debitor_name not in debitor_map:
        debitor_map[debitor_name] = set()
    # 添加实体ID到集合(自动去重重复的ID)
    debitor_map[debitor_name].add(entity_id)

# 转换为目标格式的列表
agg_debitor_list = [(list(ids), name) for name, ids in debitor_map.items()]

方式2:用列表保持ID出现顺序

如果需要严格保留实体ID第一次出现的顺序,可以用列表+存在性判断的方式:

debitor_map = {}
for entity_id, debitor_name in debitor_list:
    if debitor_name not in debitor_map:
        debitor_map[debitor_name] = []
    # 仅当ID未存在时添加,避免重复
    if entity_id not in debitor_map[debitor_name]:
        debitor_map[debitor_name].append(entity_id)

agg_debitor_list = [(ids, name) for name, ids in debitor_map.items()]

测试验证

针对输入示例:

debitor_list = [("1", "X AG"), ("1", "X AG"), ("1", "Z AG"), ("2", "X AG"), ("2", "X AG")]

运行代码后,agg_debitor_list的输出为:

[(['1', '2'], 'X AG'), (['1'], 'Z AG')]

完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:20:32