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

如何在Python列表中定位新增的重复名称及其索引?

解决列表最后20项中新增重复项的识别问题

问题需求

需要扫描两个名称列表的最后20项,找出其中新增的名称及其在新列表中的索引。现有方案在新增名称为列表已存在的重复项时失效(例如示例中new列表新增了重复的Andre),另一尝试的代码因逻辑错误无法处理元素偏移的情况。

原代码问题分析

集合差集方案

new = ['Bram', 'Vincent', 'Arthur', 'Perry', 'Bram', 'Sebastiaan', 'Arkadiusz', 'Felix', 'Suzanne', 'Maurice', 'Mohahmed', 'Lars', 'De Wet', 'Andre', 'Arjan', 'Frans', 'Andre', 'Guleed', 'Sebastian', 'Mark', 'Anne-marijke']
old = ['Bram', 'Vincent', 'Arthur', 'Perry', 'Bram', 'Sebastiaan', 'Arkadiusz', 'Felix', 'Suzanne', 'Maurice', 'Mohahmed', 'Lars', 'De Wet', 'Andre', 'Arjan', 'Frans', 'Guleed', 'Sebastian', 'Mark', 'Anne-marijke', 'Karel']

newname = list(set(new) - set(old))
  • 集合的特性是自动去重,所以即使new中新增了重复的Andre,由于old中已存在该元素,差集结果为空,无法识别这类新增的重复项。

尝试的遍历方案

newname = None
for x in range(20):

    if new[x] == old[x]:
        continue
    if new[x] == old[x - 1]:
        continue
    if new[x] == old[+1]:
        continue
    else:
        newname = new[x]

print(newname)
  • 逻辑错误:old[+1]是固定取索引1的元素,并非x+1;
  • 仅返回最后一个符合条件的元素,未记录索引;
  • 未针对列表最后20项处理,也未正确处理元素插入导致的后续元素偏移问题。

解决方案:双指针匹配法

通过双指针遍历两个列表的最后20项,精准匹配元素,找出新增项及其原索引:

new = ['Bram', 'Vincent', 'Arthur', 'Perry', 'Bram', 'Sebastiaan', 'Arkadiusz', 'Felix', 'Suzanne', 'Maurice', 'Mohahmed', 'Lars', 'De Wet', 'Andre', 'Arjan', 'Frans', 'Andre', 'Guleed', 'Sebastian', 'Mark', 'Anne-marijke']
old = ['Bram', 'Vincent', 'Arthur', 'Perry', 'Bram', 'Sebastiaan', 'Arkadiusz', 'Felix', 'Suzanne', 'Maurice', 'Mohahmed', 'Lars', 'De Wet', 'Andre', 'Arjan', 'Frans', 'Guleed', 'Sebastian', 'Mark', 'Anne-marijke', 'Karel']

# 截取两个列表的最后20项
new_last20 = new[-20:]
old_last20 = old[-20:]

i = j = 0
added_items = []

# 双指针匹配元素
while i < len(new_last20) and j < len(old_last20):
    if new_last20[i] == old_last20[j]:
        i += 1
        j += 1
    else:
        # 计算新增元素在原new列表中的索引
        original_index = len(new) - 20 + i
        added_items.append((original_index, new_last20[i]))
        i += 1

# 处理new_last20中剩余的新增元素
while i < len(new_last20):
    original_index = len(new) - 20 + i
    added_items.append((original_index, new_last20[i]))
    i += 1

# 输出结果
print("新增的名称及其索引:")
for idx, name in added_items:
    print(f"索引:{idx},名称:{name}")

代码说明

  1. 聚焦目标范围:先截取两个列表的最后20项,避免遍历整个列表;
  2. 双指针匹配:同步遍历两个子列表,元素匹配时同时移动指针,不匹配时记录new_last20中的当前元素为新增项;
  3. 索引转换:将子列表中的索引转换为原new列表中的真实索引;
  4. 剩余元素处理:如果new_last20遍历结束后还有未匹配的元素,全部视为新增项。

运行结果

新增的名称及其索引:
索引:16,名称:Andre

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:40:34