0

I have a list of strings where the strings have lists. I want to return a list of lists.

Here is what I might start with:

old_list = ['[1,2,m]','[4.1,3.5,5]','[x,y,z]', '["t","u","v"]']

Here is what I would want:

new_list = [[1,2,'m'],[4.1,3.5,5],['x','y','z'],['t','u','v']]
  • 1
    Why do you have quotes around the string elements sometimes, but not other times? Can you fix the source so it adds the quotes consistently? – Barmar Jun 08 '19 at 21:15
  • Possible duplicate of [How to return a list of lists from a list of strings with lists in the strings](https://stackoverflow.com/questions/56509445/how-to-return-a-list-of-lists-from-a-list-of-strings-with-lists-in-the-strings) – Finomnis Jun 08 '19 at 21:34
  • It wasn't fully answered there –  Jun 08 '19 at 21:37
  • And that is a reason to re-post it? I think you are missing the point of how stackoverflow works. – Finomnis Jun 11 '19 at 10:36
  • Sharing information on coding is not the point? –  Jun 12 '19 at 11:13

1 Answers1

3

Looks like a case where you have to build your own hammer, so to speak. Use a combination of literal_eval where you can, and then build a custom parser where you can't. You may need to add more cases as needed.

from ast import literal_eval

old_list = ['[1,2,m]','[4.1,3.5,5]','[x,y,z]', '["t","u","v"]']

def hierarchical_convert(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return(s)

new_lst = []
for s in old_list:
    try:
        out = literal_eval(s)
    except ValueError: #need to split on comma ourselves, and invoke custom parsing
        out = [hierarchical_convert(item) for item in s[1:-1].split(',')]
    new_lst.append(out)


print(new_lst)
#Output
[[1, 2, 'm'], [4.1, 3.5, 5], ['x', 'y', 'z'], ['t', 'u', 'v']]
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
  • 4
    answer to a question like this can only be a hack. I appreciate the passes, increasing the hack level, to improve the chance of parsing it right. Excellent answer. – Jean-François Fabre Jun 08 '19 at 21:18