Home > Back-end >  How can I merge consecutive string items in a sublist in Python?
How can I merge consecutive string items in a sublist in Python?

Time:10-05

I want to remove special character from all the elements of a sublist in a list. How can I do so?

list = [['abch', 'def',1,11],['cdjje', 'fef',2,22],['oefg', 'pqkjbr',3,33]]

'abc', 'def' is one string and ', ' is supposed to be replaced with a space. Output is expected to be:

    list = [['abch def',1,11],['cdjje fef',2,22],['oefg pqkjbr',3,33]]

I am trying below code but it doesn't seem to work:

value_list=[]
for idx, item in enumerate(list):
    value_list[idx] = re.sub(r"', '"," ", str(item[0:-2]))
    print(value_list)

CodePudding user response:

I hope this is what you are looking for. $ has special meaning in regex (should match the end of the string), therefore use backslash $.

output_list = l_list.copy()
for l_idx, l_item in enumerate(l_list):
    for i_idx, i_item in enumerate(l_item):
        if isinstance(i_item, str):
            output_list[l_idx][i_idx] = re.sub(r"\$","", i_item)
print(output_list)

CodePudding user response:

You can use

lst = [['abc', 'def',1,11],['cde', 'fef',2,22],['efg', 'pqr',3,33]]
result = []
for l in lst:
    res = []
    for i, s in enumerate(l):
        if isinstance(s, str):
            if len(res) > 0 and isinstance(res[i-1], str):
                res[i-1]  = f" {s}"
            else:
                res.append(s)
        else:
            res.append(s)
    result.append(res)

print(result)
# => [['abc def', 1, 11], ['cde fef', 2, 22], ['efg pqr', 3, 33]]

See the Python demo. NOTE: Do not name your variables as built-ins, list is a Python built-in, and you can use other names for lists, like lst, l, etc.

CodePudding user response:

This:

import re

thelist = [['abc$', 1, 11], ['cde$', 2, 22],['efg$', 3, 33]]
regex = re.compile(r'\$')

newlist = [[regex.sub('', x) if isinstance(x, str) else x for x in l] for l in thelist]
print(newlist)

Prints:

[['abc', 1, 11], ['cde', 2, 22], ['efg', 3, 33]]

For new question:

This:

thelists = [['abch', 'def', 1, 11], ['cdjje', 'fef', 2, 22], ['oefg', 'pqkjbr', 3, 33]]

newlist = []

for thelist in thelists:
    tmplist = []
    for item in thelist:
        if len(tmplist) and isinstance(item, str) and isinstance(tmplist[-1], str):
            tmplist[-1]  = item
        else:
            tmplist.append(item)
    newlist.append(tmplist)
       

print(newlist)

Prints:

[['abchdef', 1, 11], ['cdjjefef', 2, 22], ['oefgpqkjbr', 3, 33]]
  • Related