如何从python中删除字符串中的重复记录?我的方法都被拒绝了。以下是我的代码

时间:2017-03-17 09:02:13

标签: python

这是我的代码,我一直坚持,任何人都指出这里有什么问题,或者建议我采用另一种方法来实现这一目标。

def remove_duplicates(string):

    s = string.split()
    return string.replace(s[0],"")

def RemoveDupliChar(Word):
        NewWord = " "
        index = 0
        for char in Word:
                if char != NewWord[index]:
                        NewWord += char
                        index += 1
        print(NewWord.strip()) 

3 个答案:

答案 0 :(得分:0)

如果可能,请尝试添加至少一个示例。 它有助于理解问题。

以下是您的解决方案的一个可能示例(根据您对您的问题的理解。)

>>> def func1(str1):
...     strarr1 = str1.split()
...     tempstr = []
...     for i in strarr1:
...             if i not in tempstr:
...                     tempstr.append(i);
...     print (tempstr)
...
  

示例:输入:func1("他是他,你好,嘿嘿嘿嘿嘿嘿嘿")

     

输出:['他','你好'' bolo',' bo',' hee' ]

或许这就是你想要的:

>>> def func2(str1):
...     str2arr=[]
...     str3arr=[]
...     str4 = ''
...     for i in str1:
...             if i not in str2arr:
...                     str2arr.append(i)
...             else:
...                     str3arr.append(i)
...     print (str2arr)
...
  

示例输入:func2(" heeelo")

     

输出:[' h',' e'' l',' o']

答案 1 :(得分:0)

我认为这可能会有所帮助。

def removeDupWords(list):
    newList = []
    for x in list:
        if x not in newList:
            newList.append(x)
    return newList

s="Hello World World Hello"
output=' '.join(removeDupWords(s.split(' ')))
print(output)
  

输出:Hello World

答案 2 :(得分:0)

def removeDupWords(list):
    newList = []
    tuple = []
    duplicates = 0
    for x in list:
        if x not in newList:
            newList.append(x)
        else:
            duplicates += 1
    uniqueString = ''.join(sorted(newList))
    tuple.append(uniqueString)
    tuple.append(duplicates)
    return tuple

s="hellohowareyou"
output=removeDupWords(s)
print(output)
  

输出:

     

['aehloruwy',5]