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

如何实现支持字符串、列表、字典、元组的通用去重功能?

Universal Duplicate Remover for Multiple Data Types

Got it, let's upgrade your function to handle strings, lists, tuples, and dictionaries as you need! The original code only works for strings, so we'll build a flexible solution that maintains the order of first occurrences (just like your examples) and handles each data type appropriately.

The Solution Code

def remove_duplicates(data):
    # Handle strings: preserve order of first occurrence
    if isinstance(data, str):
        seen = set()
        result_chars = []
        for char in data:
            if char not in seen:
                seen.add(char)
                result_chars.append(char)
        return ''.join(result_chars)
    
    # Handle lists: keep only first occurrence of each item
    elif isinstance(data, list):
        seen = set()
        result_list = []
        for item in data:
            if item not in seen:
                seen.add(item)
                result_list.append(item)
        return result_list
    
    # Handle tuples: same logic as lists, return a tuple
    elif isinstance(data, tuple):
        seen = set()
        result_items = []
        for item in data:
            if item not in seen:
                seen.add(item)
                result_items.append(item)
        return tuple(result_items)
    
    # Handle dictionaries: per your example, keep all unique keys, set values to 1
    elif isinstance(data, dict):
        # Dictionary keys are already unique by definition, so we just map each key to 1
        return {key: 1 for key in data.keys()}
    
    # Raise error for unsupported types
    else:
        raise TypeError("Unsupported data type. Please pass a string, list, tuple, or dictionary.")

How It Works

Let's break down each part to match your requirements:

  • Strings: We use a set (seen) to track characters we've already encountered (this is much faster than your original count() method for large inputs). We build a list of characters in their first-occurrence order, then join it back into a string.
  • Lists: Same logic as strings—track seen items with a set, build a list of unique items in original order.
  • Tuples: Since tuples are immutable, we process them like lists, then convert the result back to a tuple.
  • Dictionaries: Dictionary keys are inherently unique, so we just create a new dictionary where every existing key maps to 1, exactly matching your example output.

Test It Out

Run these test cases to verify it works as expected:

# Test 1: String input
print(remove_duplicates("AAAAABBBBSSSSS"))  # Output: "ABS"

# Test 2: List input
print(remove_duplicates([1,2,4,3,2,2,2]))   # Output: [1, 2, 4, 3]

# Test 3: Dictionary input
print(remove_duplicates({"hello": 3, "hi": 1 , "bye" : 2}))  # Output: {'hello': 1, 'hi': 1, 'bye': 1}

# Test 4: Tuple input
print(remove_duplicates((1,2,3,3,4,4)))     # Output: (1, 2, 3, 4)

If you need to adjust the dictionary logic (e.g., remove keys with duplicate values instead), just tweak the dictionary handling block—happy to help refine that further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:03:16