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

如何编写程序移除列表中重复项间元素及第二个重复项

Python Solution to Remove Elements Between Duplicate Pairs

How It Works

We use a while loop to step through the input list, keeping track of elements we've already added to our result with a dictionary (so we can quickly find where an element first appeared):

  • When we hit an element we haven't seen before, we add it to the result and note its position.
  • If we encounter an element we've already added:
    • Cut the result list off right after the first occurrence of this element (keeping only the first instance, ditching everything after it in the result).
    • Reset our tracking dictionary to match the shortened result.
    • Skip ahead in the input list until we pass the second duplicate (removing it and everything between the two duplicates).
  • Repeat until we've processed the entire input list.

Code

def process_duplicate_pairs(input_list):
    result = []
    seen = {}
    i = 0
    n = len(input_list)
    
    while i < n:
        current_elem = input_list[i]
        
        if current_elem not in seen:
            seen[current_elem] = len(result)
            result.append(current_elem)
            i += 1
        else:
            # Truncate result to retain only up to the first occurrence
            result = result[:seen[current_elem] + 1]
            # Reset tracking dict for the updated result
            seen = {elem: idx for idx, elem in enumerate(result)}
            # Skip past the second duplicate element
            while i < n and input_list[i] != current_elem:
                i += 1
            i += 1  # Move to the next element after the duplicate
    
    return result

Test Examples

Example 1

a = [(0,0),(1,0),(2,0),(3,0),(1,0)]
print(process_duplicate_pairs(a))  # Output: [(0, 0), (1, 0)]

Example 2

b = [(0,0),(1,0),(2,0),(3,0),(1,0),(5,0),(6,0),(7,0),(8,0),(5,0),(9,0),(10,0)]
print(process_duplicate_pairs(b))  # Output: [(0, 0), (1, 0), (5, 0), (9, 0), (10, 0)]

Note: The expected result in the problem statement for example 2 omits (10,0), but since this element has no duplicates, it should be retained in the output as per the problem's description.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:50:46