-3

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']]
peachii
  • 1
  • 3
  • Please provide a complete example, that others can run and that shows the problem. You say "input is [p[da]" - do you mean the function is called with parameter `p` set to `'[p[da]'`? Or... – Grismar Dec 10 '21 at 03:23
  • Hi sorry for the confusion. I have edited the post. – peachii Dec 10 '21 at 03:26

2 Answers2

0

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
Grismar
  • 27,561
  • 4
  • 31
  • 54
0

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.

Kanishk
  • 258
  • 1
  • 3
  • 9