我有一个字符串 'aabbababacccssdd'
我想从中生成 ['aa', 'bb', 'a', 'b', 'a', 'b' , 'a', 'ccc', 'ss', 'dd']
这是我目前的解决方案:
def get_pats(n):
n = str(n) # to support integers
a = len(n)
p = []
pat_start = 0
prev = 0
for b in range(0, a):
if n[b] != n[prev]:
p.append(n[pat_start:b])
prev = b
pat_start = b
p.append(n[pat_start:b+1])
return p
该解决方案效果很好,但我想知道是否有更优雅/pythonic 的方式来做到这一点?
最佳答案
这就是itertools.groupby为你做的:
text = 'aabbababacccssdd'
from itertools import groupby
print [''.join(g) for k, g in groupby(text)]
# # ['aa', 'bb', 'a', 'b', 'a', 'b', 'a', 'ccc', 'ss', 'dd']
关于python - 如何在 python ( 'aabcdd' -> ['aa' , 'b' , 'c' , 'dd' ] ) 中对相同字符的句子进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15465519/