Python - 当字符与前一个字符不同时,拆分已排序的字符串

时间:2014-10-29 03:36:34

标签: python string python-3.x split

我有一串我知道要排序的字符。例如:

myString = "aaaabbbbbbcccddddd"

我希望将此项目拆分为当我所在的角色与其前一个角色不同时的列表,如下所示:

splitList = ["aaaa","bbbbbb","ccc","ddddd"]

我正在使用Python 3.4。

谢谢!

2 个答案:

答案 0 :(得分:1)

In [294]: myString = "aaaabbbbbbcccddddd"

In [295]: [''.join(list(g)) for i,g in itertools.groupby(myString)]
Out[295]: ['aaaa', 'bbbbbb', 'ccc', 'ddddd']

答案 1 :(得分:0)

myString = "aaaabbbbbbcccddddd"
result = []
for i,s in enumerate(myString):
    l = len(result)
    if  l == 0 or s != myString[i-1]:
        result.append(s)
    else:
        result[l-1] = result[l-1] + s

print result

输出:

['aaaa', 'bbbbbb', 'ccc', 'ddddd']