【问题标题】:Given a string how can I remove all the duplicated consecutive letters?给定一个字符串,如何删除所有重复的连续字母?
【发布时间】:2018-11-29 18:53:31
【问题描述】:

如何从字符串中删除两个连续的字母?

例如:

a_str = 'hii thherre'

应该变成

'hi there'

我尝试过:

a_str = ''.join(sorted(set(a_str), key=a_str.index))

但是,我得到:

'hi ter'

【问题讨论】:

  • 三个或四个连续的字母呢?
  • 任务是删除两个连续的字母,但您编写的代码是删除除第一个字母之外的所有字母。你应该更加努力地自己解决这个问题; SO 既不是代码编写也不是教程服务。
  • @timgeb,是的,也可以考虑
  • 如果一个单词实际上有双字母怎么办?例如three 而不是threee

标签: python string python-3.x list-comprehension


【解决方案1】:

是的,[三个或四个连续的字母]也可以考虑

在那种情况下,如果我理解正确的话,你只想取每个连续相等字母序列中的一个。考虑itertools.groupby

>>> from itertools import groupby
>>> a_str = 'hii thherre'
>>> ''.join(k for k, _ in groupby(a_str))
'hi there'

编辑:奖励正则表达式

>>> import re
>>> re.sub(r'(.)\1*', r'\1', a_str)
'hi there'

【讨论】:

    【解决方案2】:

    您可以通过迭代所有字符及其下一个元素的组合并选择不相等的元素来做到这一点。

    from itertools import zip_longest
    
    a_str = 'hii thherre'
    new_a = ''.join(i[0] for i in zip_longest(a_str, a_str[1:]) if i[0] != i[1])
    
    print(new_a) # -> hi there
    

    【讨论】:

    • 花了我一秒钟才弄清楚为什么它必须是zip_longest ;)
    【解决方案3】:

    没有导入的直接 python,

    拆分字符串,检查下一个字符是否相同,如果相同,删除它。

    a_str = 'hii thherre'
    e = list(a_str)
    b_str = ""
    for i, x in enumerate(e):
        nextelem = e[(i + 1) % len(e)]
        if nextelem == x:
            print("Duplicate found, removing")
        else:
            b_str = b_str + x
    
    print(b_str)
    

    【讨论】:

      【解决方案4】:

      另一个纯Python版本,函数式风格:

      import operator
      
      getter = operator.itemgetter(1)
      it = iter(s)
      result = next(it) + ''.join(map(getter, filter(lambda x: x[0] != x[1], zip(s, it))))
      

      或者,避免导入:

      it = iter(s)
      result = next(it) + ''.join(map(lambda x: x[1], filter(lambda x: x[0] != x[1], zip(s, it))))
      

      【讨论】:

        【解决方案5】:

        简单的方法,使用 for-loopif-condition

        a_str = 'hii thherre'
        s = a_str[0]
        for i in range(1, len(a_str)):
            if(a_str[i-1] != a_str[i]): s += a_str[i]
        print(s) #hi there
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-17
          • 1970-01-01
          • 1970-01-01
          • 2017-10-29
          • 2015-01-26
          • 1970-01-01
          • 2018-03-23
          • 1970-01-01
          相关资源
          最近更新 更多