I want to make a list inside a list
def makelist(s):
res = []
for samp in s:
res = list(samp.lstrip('[').rstrip(']'))
return res
- s = '[p[da]]'
- output is ['p','d','a']
- but I want to add list inside to make it look like this ['p'['d','a']]
CodePudding user response:
You are looping over a string (s
, with value '[p[da]]'
), so samp
will be each character in the string in turn ('['
, 'p'
, etc.) - you then proceed to strip off brackets, and turn the result into a list of characters. That list will always be either empty if the character was a bracket, or the character if it was not. Your code does nothing to group nested brackets, or anything of the sort.
A non-recursive solution:
def makelist(s):
part = []
stack = []
for ch in s:
if ch == '[':
part.append([])
stack.append(part)
part = part[-1]
elif ch == ']':
if stack:
part = stack.pop()
else:
raise SyntaxError('Too many closing brackets')
else:
part.append(ch)
if stack:
raise SyntaxError('Too many opening brackets')
return part
print(makelist('[p[da]]'))
print(makelist('[a[b[c]d]e]'))
print(makelist('123'))
try:
print(makelist('[a]]'))
except Exception as e:
print(e)
try:
print(makelist('[[a]'))
except Exception as e:
print(e)
Result:
[['p', ['d', 'a']]]
[['a', ['b', ['c'], 'd'], 'e']]
['1', '2', '3']
Too many closing brackets
Too many opening brackets
CodePudding user response:
Firstly, I am sorry for this solution. Am laughing at myself for what I just wrote. I had to make many assumptions due to the lack of information about the input parameter.
import ast
def string_to_list(string: str):
def sort_the_sting(string: str):
return string.replace("]'", "],'").replace("][", "],[").replace("'[", "',[").replace("''", "','")
strval = ""
for character in string:
strval = "".join(("'", character, "'") if character.isalpha() else (character))
return ast.literal_eval(sort_the_sting(strval))
You can replicate your example by string_to_list("[p[da]]")
Whats happening in the fucntion: the for loop iterates over the characters of the given string, adding '
each side of a alphabetic character. then by replacing some combinations of characters you end up with serialized string ready to be converted into a list object.