Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing,splicing and structuring nested strings to list in Python

I can't imagine I'm going to get much help from this due to my inability to explain it. But for instance I have a string like so:

s = "[1,[2,2,[3,4]],5]"

and I need to convert it into a nested list item as such

lst = ["1",["2","2",["3","4"]],"5"]

that if I were to go lst[1][2][0] it would return '3'.

The way I have tried to do it was by creating a substring for every number within '[' and end of string characters and then slowly nest it back up

def ParseList(strlist):
    if '[' in strlist:
        print strlist
        return ParseList(GetBetweenChar(strlist,'[',None))
    else:
        return strlist

however it returns:(which although maybe a good start? I dont know where to continue)

[1,[2,2,[3,4]],5]
 1,[2,2,[3,4]],5
 2,2,[3,4]],
 3,4]]

which I would think I would append that to a list item but I dont know how to..

like image 385
Evan Maltby Avatar asked Mar 27 '26 02:03

Evan Maltby


1 Answers

You can use ast.literal_eval to safely convert the string to a nested list of integers. Then define a nested map function to convert to all elements to strings, whilst maintaining the nesting structure.

from ast import literal_eval
s = "[1,[2,2,[3,4]],5]"
ls = literal_eval(s)

# yes I know there is something else called nmap 
def nmap(fn, iterable):
    res = []
    for i in iterable:
        if isinstance(i, list): # could be tuple or something else?
            res.append(nmap(fn, i))
        else:
            res.append(fn(i))
    return res

result = nmap(str, ls)

print(result)
print(result[1][2][0])

result:

['1', ['2', '2', ['3', '4']], '5']
3

like image 75
Paul Rooney Avatar answered Mar 29 '26 16:03

Paul Rooney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!