2012-02-29 166 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']