【问题标题】:How do I slice a string by characters in Python? [duplicate]如何在 Python 中按字符对字符串进行切片? [复制]
【发布时间】:2019-03-16 08:38:53
【问题描述】:

有一个包含一个或多个字符的字符串。我想对列表进行切片,以便相邻的相同字符位于同一元素中。例如:

'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']

如何在 Python 中实现这一点?

【问题讨论】:

  • 仅供参考,如果您在 google 上搜索“python 组相同元素”或类似内容,您会发现很多可以帮助您入门的食谱。

标签: python


【解决方案1】:

使用itertools.groupby:

from itertools import groupby

s = 'abccbba'

print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']

【讨论】:

    【解决方案2】:

    可以通过re.finditer()实现:

    import re
    s = 'aabccdd'
    print([m.group(0) for m in re.finditer(r"(\w)\1*", s)])
    #['aa', 'b', 'cc', 'dd']
    

    【讨论】:

      【解决方案3】:

      没有任何模块并使用for 循环也可以以一种有趣的方式完成:

      l = []
      str = "aabccc"
      s = str[0]
      for c in str[1:]:
      
          if (c != s[-1]):
              l.append(s)
              s = c
          else:
              s = s + c
      l.append(s)
      print(l)
      

      【讨论】:

        【解决方案4】:

        只是另一种解决方案。在 Python 2 中您不需要对其进行任何导入。在 Python 3 中,您需要从 functools 导入。

        from functools import reduce   # In Python 3
        s = 'aaabccdddddaa'
        reduce(lambda x, y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, [])
        

        【讨论】:

        • 哇……这简直是难以理解……
        【解决方案5】:
        t = input()
        c = [t[0]]
        for i in range(1, len(t)):
            if t[i] == c[-1][0]:
                c[-1] = c[-1] + t[i]
            else:
                c.append(t[i])
        print(c)
        

        【讨论】:

        • 请添加一些文字以使答案更具描述性。
        猜你喜欢
        • 1970-01-01
        • 2021-03-12
        • 1970-01-01
        • 2012-11-20
        • 2011-12-03
        • 2012-07-13
        • 2017-04-21
        • 2021-11-20
        • 2014-07-08
        相关资源
        最近更新 更多