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

如何修改Python脚本实现IDN字符串按规则去重

问题:IDN类型字符串列表按IDN值去重(仅保留首次出现的条目)

我编写了如下Python脚本,用于对包含IDN类型的字符串列表进行去重:

unique=[]

thislist =['idn_type1=:111-22-3333',
'idn_type1=:111-22-3333',
'idn_type1=:222-33-4444',
'idn_type2=:333-44-5555',
'idn_type2=:222-33-4444',
'idn_type3=:222-33-4444',
'idn_type4=:222-33-4444',
'idn_type1=:',
'idn_type1=:444-55-6666',
'idn_type1=:555-66-7777',
'idn_type1=:']

for name in thislist:
      if name not in unique and name.partition(':')[-1] not in unique and name.partition(':')[-1]!='':
            unique.append(name)

for i in range(len(unique)):
    print(unique[i])

但运行结果不符合预期,错误输出为:

idn_type1=:111-22-3333
idn_type1=:222-33-4444
idn_type2=:333-44-5555
idn_type2=:222-33-4444
idn_type3=:222-33-4444
idn_type4=:222-33-4444
idn_type1=:444-55-6666
idn_type1=:555-66-7777

我的期望输出是:

idn_type1=:111-22-3333
idn_type1=:222-33-4444
idn_type2=:333-44-5555
idn_type1=:444-55-6666
idn_type1=:555-66-7777

需求:当IDN值(如'222-33-4444')首次出现时,仅将该条目添加到结果列表中,后续其他类型下的相同IDN值不再添加。请问该如何修改脚本?

感谢Martineau修正我的描述!


解决方案

原脚本的核心问题是:用name.partition(':')[-1] not in unique判断IDN值是否已存在,但unique列表存储的是完整的条目字符串(如idn_type1=:222-33-4444),IDN值本身永远不在该列表中,导致相同IDN的不同类型条目都会被加入。

正确的做法是维护一个单独的集合,专门记录已经处理过的有效IDN值,具体修改如下:

unique = []
seen_idns = set()  # 用于存储已出现的IDN值

thislist =['idn_type1=:111-22-3333',
'idn_type1=:111-22-3333',
'idn_type1=:222-33-4444',
'idn_type2=:333-44-5555',
'idn_type2=:222-33-4444',
'idn_type3=:222-33-4444',
'idn_type4=:222-33-4444',
'idn_type1=:',
'idn_type1=:444-55-6666',
'idn_type1=:555-66-7777',
'idn_type1=:']

for name in thislist:
    idn_value = name.partition(':')[-1]
    # 仅当IDN值非空且未被记录过时,才添加条目并记录IDN
    if idn_value != '' and idn_value not in seen_idns:
        unique.append(name)
        seen_idns.add(idn_value)

# 输出结果
for item in unique:
    print(item)

逻辑说明:

  1. 新增seen_idns集合,用于快速判断IDN值是否已出现(集合的查询效率远高于列表)
  2. 遍历每个条目时,先拆分出IDN值
  3. 仅当IDN值非空且未在seen_idns中时,才将当前条目加入unique列表,并把IDN值存入集合
  4. 这样就能保证每个IDN值只保留第一次出现的条目,后续相同IDN的其他条目都会被过滤

运行上述代码后,输出将与期望结果完全一致。


内容的提问来源于Stack Exchange,提问作者Stanley1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:24:11