I want to merge all the strings present in the list into single string, if they lie between ‘zz’ using python
old_list = ['1', 'zz', '1', '2', 'zz', '1', '1', '1', 'zz', '1', 'zz']
Expected output:
new_list = ['1', '11', '111', '1']
>Solution :
Solution with itertools.groupby:
from itertools import groupby
old_list = ["1", "zz", "1", "1", "zz", "1", "1", "1", "zz", "1", "zz"]
new_list = []
for k, g in groupby(old_list, lambda k: k == "zz"):
if not k:
new_list.append("".join(g))
print(new_list)
Prints:
['1', '11', '111', '1']