Python:从字符串中删除重复字符的最佳方法

12

如何使用Python从字符串中删除重复的字符?例如,假设我有一个字符串:

foo = "SSYYNNOOPPSSIISS"

如何将字符串变为:

foo = SYNOPSIS

我是Python的新手,我尝试了以下内容并且它能够正常工作。我知道还有更聪明和更好的方法来完成这个任务,只有经验才能证明。

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

注意: 顺序很重要,这个问题与这个不同。

7个回答

20

使用itertools.groupby

>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'

1
能否将 grp 更改为 _? - Roman Pekar
@RahulPatil,“_”(在答案修改之前的“grp”)是可迭代的,它会产生被分组在一起的单个项(这里是字符)。 - falsetru
我花了一些时间来创建那个函数,我不知道itertools.groupby是怎么找到的? - Rahul Patil
2
@RahulPatil 它通常作为占位符名称在循环中使用。你从不使用它,但是它被放在那里是因为你需要放置一些东西。itertools.groupby是标准库中的itertools模块的一部分。在falsetru的答案中有一个链接。 - TerryA
如果您想要结果为“SYNOPSIS”,那么此代码将按照所示方式工作。但是,如果您希望结果为“SYNOPI”,其中没有字符重复超过一次,该怎么办呢?如果您想要从“jillll”中得到“jill”,因为“jill”是正确的拼写,又该怎么办呢? - rabin utam
显示剩余6条评论

4

这是一种无需导入itertools的解决方案:

foo = "SSYYNNOOPPSSIISS"
''.join([foo[i] for i in range(len(foo)-1) if foo[i+1]!= foo[i]]+[foo[-1]])

Out[1]: 'SYNOPSIS'

但是它比其他方法慢!


3
这个怎么样:
oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
    if char != newstring[-1]:
        newstring += char    

1
def remove_duplicates(astring):
  if isinstance(astring,str) :
    #the first approach will be to use set so we will convert string to set and then convert back set to string and compare the lenght of the 2
    newstring = astring[0]
    for char in astring[1:]:
        if char not in newstring:
            newstring += char    
    return newstring,len(astring)-len(newstring)
  else:
raise TypeError("only deal with alpha  strings")

我发现使用itertools和列表推导式的解决方案,即使将字符与列表的最后一个元素进行比较的解决方案也不起作用。

0
def removeDuplicate(s):  
    if (len(s)) < 2:
        return s

    result = []
    for i in s:
        if i not in result:
            result.append(i)

    return ''.join(result)  

0

怎么样?

foo = "SSYYNNOOPPSSIISS"


def rm_dup(input_str):
    newstring = foo[0]
    for i in xrange(len(input_str)):
        if newstring[(len(newstring) - 1 )] != input_str[i]:
            newstring += input_str[i]
        else:
            pass
    return newstring

print rm_dup(foo)

-1
你可以尝试这个:
string1 = "example1122334455"
string2 = "hello there"

def duplicate(string):
    temp = ''

    for i in string:
        if i not in temp: 
            temp += i

    return temp;

print(duplicate(string1))
print(duplicate(string2))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接