2012-02-29 82 views
8

我想分割字符串喜欢的字符串:字符串分割到重复元素

'aaabbccccabbb' 

['aaa', 'bb', 'cccc', 'a', 'bbb'] 

什么是优雅的方式在Python做到这一点?如果它更容易,可以假定该字符串只包含a,b和c。

+0

可能重复[如何拆分此字符串与Python?](http://stackoverflow.com/questions/3940721/how -to-split-this-string-with-python) – 2012-03-01 12:35:44

+1

没有人建议使用正则表达式吗?我既感到印象深刻,也感到难过。 – 2012-03-02 07:18:35

+0

是的,这是Ethan链接到的问题的重复。但是这个问题没有一个有用的标题,国际海事组织。 – Colin 2012-03-02 19:55:22

回答

26

也就是说使用情况itertools.groupby :)

>>> from itertools import groupby 
>>> s = 'aaabbccccabbb' 
>>> [''.join(y) for _,y in groupby(s)] 
['aaa', 'bb', 'cccc', 'a', 'bbb'] 
+0

我知道会有一个简单的方法来做到这一点! – Colin 2012-02-29 19:52:06

3

您可以创建一个迭代器 - 没有试图要聪明,只是为了保持它短而无法读取:

def yield_same(string): 
    it_str = iter(string) 
    result = it_str.next() 
    for next_chr in it_str: 
     if next_chr != result[0]: 
      yield result 
      result = "" 
     result += next_chr 
    yield result 


.. 
>>> list(yield_same("aaaaaabcbcdcdccccccdddddd")) 
['aaaaaa', 'b', 'c', 'b', 'c', 'd', 'c', 'd', 'cccccc', 'dddddd'] 
>>> 

编辑 好吧,所以有itertools.groupby,这可能会做这样的事情。

2

这是我能找到的使用正则表达式的最佳方法:

print [a for a,b in re.findall(r"((\w)\2*)", s)] 
1
>>> import re 
>>> s = 'aaabbccccabbb' 
>>> [m.group() for m in re.finditer(r'(\w)(\1*)',s)] 
['aaa', 'bb', 'cccc', 'a', 'bbb']