【问题标题】:Python: Best Way to remove duplicate character from stringPython:从字符串中删除重复字符的最佳方法
【发布时间】:2013-09-18 21:24:51
【问题描述】:

如何使用 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()) 

注意:顺序很重要,此问题与this one 不同。

【问题讨论】:

    标签: python string text-processing


    【解决方案1】:

    使用itertools.groupby

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

    【讨论】:

    • 可以把grp改成_吗?
    • @RahulPatil, _(答案修改前的grp)是可迭代的,它产生组合在一起的单个项目(此处的字符)。
    • 我花了一些时间来创建那个函数,我不知道itertools.groupby你是怎么发现的?
    • @RahulPatil 是否常用于循环中作为占位符名称。你从不使用它,但它被放在那里是因为你需要放一些东西。 itertools.groupby 是标准库中 itertools 模块的一部分。 falsetru的答案中有一个链接
    • @RahulPatil,我看到 Python Module Index 在标准库中找到有用的模块。
    【解决方案2】:

    这是不导入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    
      

      【讨论】:

        【解决方案4】:
        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 和列表理解的解决方案甚至当我们将 char 与列表的最后一个元素进行比较时的解决方案也不起作用

        【讨论】:

          【解决方案5】:
          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)  
          

          【讨论】:

            【解决方案6】:

            怎么样

            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)
            

            【讨论】:

              【解决方案7】:

              你可以试试这个:

              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))
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2010-10-12
                • 2016-10-30
                • 2016-11-17
                • 1970-01-01
                • 2013-08-12
                • 1970-01-01
                • 2017-12-17
                • 1970-01-01
                相关资源
                最近更新 更多