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

如何从有序嵌套列表中移除重复的Vendor ID-Vendor Name条目?

问题:移除嵌套列表中重复的供应商条目,保留对应金额条目

输入示例

[['110220VOLTS0001', 'Vendor1'],
['Functional Amount Not Invoiced:', '$56.97'],
['2729426', 'Vendor2'],
['Functional Amount Not Invoiced:', '$1,000.00'],
['2955510', 'Vendor3'],
['2955510', 'Vendor3'],
['Functional Amount Not Invoiced:', '$329.00'],
['3466873', 'Vendor4'],
['Functional Amount Not Invoiced:', '$0.48']]

需求说明

列表包含两类条目:

  • 第一类:['Vendor ID', 'Vendor Name'],可能重复出现
  • 第二类:['Functional Amount Not Invoiced:', '$ Amount'],无重复,每个金额条目对应其前面最近的供应商条目

需要移除重复的供应商条目,同时保留原列表的顺序以及对应的金额条目,最终输出如下:

[['110220VOLTS0001', 'Vendor1'],
['Functional Amount Not Invoiced:', '$56.97'],
['2729426', 'Vendor2'],
['Functional Amount Not Invoiced:', '$1,000.00'],
['2955510', 'Vendor3'],
['Functional Amount Not Invoiced:', '$329.00'],
['3466873', 'Vendor4'],
['Functional Amount Not Invoiced:', '$0.48']]

解决方案

利用集合记录已出现的供应商(将列表转为元组存入集合,因为列表不可哈希),遍历原列表时做判断:

  • 若为供应商条目(长度2且第一个元素不是固定金额标签),检查是否已在集合中,未出现则加入结果列表和集合
  • 若为金额条目,直接加入结果列表

实现代码:

input_list = [
    ['110220VOLTS0001', 'Vendor1'],
    ['Functional Amount Not Invoiced:', '$56.97'],
    ['2729426', 'Vendor2'],
    ['Functional Amount Not Invoiced:', '$1,000.00'],
    ['2955510', 'Vendor3'],
    ['2955510', 'Vendor3'],
    ['Functional Amount Not Invoiced:', '$329.00'],
    ['3466873', 'Vendor4'],
    ['Functional Amount Not Invoiced:', '$0.48']
]

seen_vendors = set()
result = []

for item in input_list:
    # 判断是否为供应商条目:长度为2且第一个元素不是金额标签
    if len(item) == 2 and item[0] != 'Functional Amount Not Invoiced:':
        vendor_tuple = tuple(item)
        if vendor_tuple not in seen_vendors:
            seen_vendors.add(vendor_tuple)
            result.append(item)
    else:
        # 金额条目直接加入
        result.append(item)

# 打印结果
for row in result:
    print(row)

输出结果

运行上述代码后,得到的结果与预期一致:

[['110220VOLTS0001', 'Vendor1'],
['Functional Amount Not Invoiced:', '$56.97'],
['2729426', 'Vendor2'],
['Functional Amount Not Invoiced:', '$1,000.00'],
['2955510', 'Vendor3'],
['Functional Amount Not Invoiced:', '$329.00'],
['3466873', 'Vendor4'],
['Functional Amount Not Invoiced:', '$0.48']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:20:30