简体   繁体   English

从数据类型中删除重复项(长字符串、列表、字典、元组)

[英]to remove duplicates from data type (long strings , list ,a dictionary, tuples)

def remove_duplicate(string):
        new = ""
        for i in string:
            if i not in new and string.count(i) >= 1:
                new += i
        return new

sample input "AAAAABBBBSSSSS"
sample output "ABS"
sample input [1,2,4,3,2,2,2]
sample output [1,2,4,3]
sample input {"hello": 3, "hi": 1 , "bye" : 2}
sample output {"hello": 1, "hi": 1 , "bye" : 1}
sample input (1,2,3,3,4,4)
sample output (1,2,3,4)

only able to solve for string and lists, above code only works for strings not able to solve for dictionaries and all data types together只能解决字符串和列表,上面的代码只适用于不能同时解决字典和所有数据类型的字符串

This is exactly what you want, the other answer is not useful about strings and dicts, also conversion to main type is skipped:这正是您想要的,另一个答案对字符串和字典没有用,还跳过了到主要类型的转换:

def remove_duplicates(input_argument):
    input_type = type(input_argument)
    if input_type is str:
        result = ''
        for character in input_argument:
            if character not in result:
                result += character
    elif input_type is dict:
        result = {}
        for key in input_argument:
            result[key] = 1  # or any other value you want
    else:
        result = input_type(set(input_argument))
    return result

Now your examples:现在你的例子:

remove_duplicates("AAAAABBBBSSSSS")
  # "ABS"
remove_duplicates([1,2,4,3,2,2,2])
  # [1,2,4,3]
remove_duplicates({"hello": 3, "hi": 1 , "bye" : 2})
  # {"hello": 1, "hi": 1 , "bye" : 1}
remove_duplicates((1,2,3,3,4,4))
  # (1,2,3,4)

You can use set to achieve the same , then convert back to the kind/type of output you want.您可以使用set来实现相同的效果,然后转换回您想要的输出种类/类型。
Something like .就像是 。

def remove_duplicate(input_parameter):
    unique =set(input_parameter)
    # Do the type conversion or format 
    # of output you want 
    
    return unique
 

It will work for all other type but for dictionary .它适用于所有其他类型,但适用于 dictionary 。 For dictionary it is not clear what you want to acheive.对于字典,尚不清楚您想要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM