我有一串我知道要排序的字符。例如:
myString = "aaaabbbbbbcccddddd"
我希望将此项目拆分为当我所在的角色与其前一个角色不同时的列表,如下所示:
splitList = ["aaaa","bbbbbb","ccc","ddddd"]
我正在使用Python 3.4。
谢谢!
答案 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']