Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to easily put all elements between 2 indexes into a nestled list in Python?

I have a list l

l = ['a','a','{','b','a','{','a','}','}','a']

I want to turn this list into the list below.

print(new_l)
# ['a','a',['{','b','a',['{','a','}'],'}'],'a']

So, basically, everything inside curly braces, including the bracces themselves should be inside a list nestled inside the original list.

Edit: Thank you all for the wonderful answers. Now, what I want the nestled lists to include the element before '{' as well? I know I should have mentioned this initially, but forgot about this requirement.

print(new_l)
# ['a',['a','{','b',['a','{','a','}'],'}'],'a']
like image 393
VoidProgrammer Avatar asked Dec 31 '22 00:12

VoidProgrammer


2 Answers

Try this

import json

def add_nested_lists(l):
    ltemp = '['
    last_element = ''
    n = len(l)
    for i in range(0, n):
        element = l[i]
        if element == '{':
            if l[i-1] == "{":
                last_element = '"{", '
                ltemp = ltemp[0:len(ltemp) - len(last_element)]
                ltemp += '[' + last_element + '"' + element + '", ' 
                last_element = '[' + last_element + '"' + element + '", ' 
            else:
                ltemp = ltemp[0:len(ltemp) - len(last_element)]
                ltemp += '[' + last_element + '"' + element + '", ' 
                last_element = '[' + last_element + '"' + element + '", ' 
        elif element == "}": 
            if i == n - 1:
                ltemp += '"' + element + '"]' + ']'
                last_element = '"' + element + '"]' + ']'
            else:
                ltemp += '"' + element + '"]' + ', '
                last_element = '"' + element + '"]' + ', '
            
        else:
            if i == 0 or i != n - 1:  # first element or  middle elements
                ltemp += '"' + element + '", ' 
                last_element = '"' + element + '", ' 
            elif i == n - 1:  # last element
                ltemp += '"' + element + '"]'
                last_element = '"' + element + '"]'
    print(ltemp)
    ltemp = json.loads(ltemp)
    return ltemp

l = ['a','a','{','{','b','a','{','a','}','}','a','}']
print(type(l), add_nested_lists(l))

Output

<class 'list'> ['a', ['a', ['{', '{', 'b', ['a', '{', 'a', '}'], '}'], 'a', '}']]

And if you can and want more efficiency then try to make string instead of list 'l' as following

import json

l = '['

last_element = ''
is_last_element_is_curly = False
def add(element, position='m'):  # m - middle element
    global l, last_element, is_last_element_is_curly
    if element == '{':
        if is_last_element_is_curly:
            last_element = '"{", '
            l = l[0:len(l) - len(last_element)]
            l += '[' + last_element + '"' + element + '", ' 
            last_element = '[' + last_element + '"' + element + '", ' 
        else:
            l = l[0:len(l) - len(last_element)]
            l += '[' + last_element + '"' + element + '", ' 
            last_element = '[' + last_element + '"' + element + '", ' 
        is_last_element_is_curly = True
    elif element == "}": 
        if position == 'l':
            l += '"' + element + '"]' + ']'
            last_element = '"' + element + '"]' + ']'
        else:
            l += '"' + element + '"]' + ', '
            last_element = '"' + element + '"]' + ', '
        is_last_element_is_curly = False
    else:
        if position == 'f' or position == 'm':  # f - first element or  m - middle element
            postfix = '", '
            l += '"' + element + '", '
            last_element = '"' + element + '", '
        elif position == 'l':  # l - last element
            l += '"' + element + '"]'
            last_element = '"' + element + '"]'
        is_last_element_is_curly = False

#Do you stuff here and add elements to string 'l'
ltemp = ['a','a','{','{','b','a','{','a','}','}','a','}']
add(ltemp[0], position="f")
for i in range(1,len(ltemp) - 1):
    add(ltemp[i])
add(ltemp[i + 1], position="l")
print(l)

#After that it will become very efficient
l = json.loads(l)
print(type(l),l)
like image 154
Navpreet Devpuri Avatar answered Jan 13 '23 18:01

Navpreet Devpuri


Look into pyparsing.

from pyparsing import nestedExpr

l = ['a','a','{','b','a','{','a','}','}','a']
l.insert(0, "{")
l.insert(len(l), "}")

print(nestedExpr('{','}').parseString(" ".join(l)).asList())

Will output:

[['a', 'a', ['b', 'a', ['a']], 'a']]

Which is not the exact output you are looking for, but perhaps a start. From here you can just access each nested list and add { and } to them.

like image 44
Felipe Avatar answered Jan 13 '23 16:01

Felipe