Home > Blockchain >  merge strings lying between two specific values
merge strings lying between two specific values

Time:06-22

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']

CodePudding user response:

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']

CodePudding user response:

Here without external libary

def filter_list(input_list):
    out = []
    zz_index = 1
    if input_list[0] != 'zz':
        zz_index  = 1
    cur_item = ""
    for i in input_list:
        if i == 'zz':
            zz_index  = 1
            out.append(cur_item)
            cur_item = ""
            zz_index = 0
        else:
            cur_item  = i
    return out
  • Related