如何拆分字符串以将 python3 中的重复项合并在一起
How to split a string to to merge the repeat items together in python3
如何按以下方式拆分字符串:
a = "111554222117"
我的目标是将字符串拆分成几段,其中连续重复的将组合在一起。输出将是一个列表
b = ['111','55','4','222','11','7']
PS: 不能像itertools
那样使用工具,因为这是一道面试题。
我的尝试是至少使用两个for
循环,但没有效果。如何只使用一个 loop
.
谢谢。
你可以这样做:
>>> import itertools
>>> [''.join(data) for _, data in itertools.groupby("111554222117")]
['111', '55', '4', '222', '11', '7']
a = "111554222117"
b = []
s = a[0]
for i in range(1,len(a)):
if a[i] == s[0]:
s += a[i]
else:
b.append(s)
s = a[i]
b.append(s)
如何按以下方式拆分字符串:
a = "111554222117"
我的目标是将字符串拆分成几段,其中连续重复的将组合在一起。输出将是一个列表
b = ['111','55','4','222','11','7']
PS: 不能像itertools
那样使用工具,因为这是一道面试题。
我的尝试是至少使用两个for
循环,但没有效果。如何只使用一个 loop
.
谢谢。
你可以这样做:
>>> import itertools
>>> [''.join(data) for _, data in itertools.groupby("111554222117")]
['111', '55', '4', '222', '11', '7']
a = "111554222117"
b = []
s = a[0]
for i in range(1,len(a)):
if a[i] == s[0]:
s += a[i]
else:
b.append(s)
s = a[i]
b.append(s)