0

I'm trying to convert a list of lists passed as string to nested list in python-3.7.5 and I'm missing something. I tried ast but it seems to be throwing an encoding error.

Example:

#!/usr/bin/env python

import ast
sample="[1abcd245,2bcdasdf,3jakdshfkh234234],[234asdfmnkk234]"
print(ast.literal_eval(sample))
ERROR:

    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    [1abcd245,2bcdasdf,3jakdshfkh234234],[234asdfmnkk234]
Required output:
[[1abcd245,2bcdasdf,3jakdshfkh234234],[234asdfmnkk234]]

Any suggestions?

3 Answers 3

2

You may use the eval() function here, after making two changes to your starting string:

  1. Wrap each list item in double quotes
  2. Wrap the entire input in [...] to make it a formal 2D list
sample = "[1abcd245,2bcdasdf,3jakdshfkh234234],[234asdfmnkk234]"
sample = '[' + re.sub(r'(\w+)', r'"\1"', sample) + ']'
list = eval(sample)
print(list)

This prints:

[['1abcd245', '2bcdasdf', '3jakdshfkh234234'], ['234asdfmnkk234']]
Sign up to request clarification or add additional context in comments.

1 Comment

Feels like your answer is the closest I could get. Was hoping ast might have solution for this.
2

I think the issue is that literal_eval is unable to parse the strings within the sample you provide. I was able to get the output you wanted by adding a triple quote to surround the sample string, adding quotes to each string within the lists and adding an extra set of brackets:

import ast
sample="""[["1abcd245","2bcdasdf","3jakdshfkh234234"],["234asdfmnkk234"]]"""
print(ast.literal_eval(sample))

In the case you cannot change the input I would recommend using the json library:

import json
json.loads(sample)

Which on my machine gets the desired result!

3 Comments

I cannot change the input, here.
if sample= "[1abcd245,2bcdasdf,3jakdshfkh234234],[234asdfmnkk234]", then json.loads also errors out. Error: File "python-3.7.5/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "python-3.7.5/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "python-3.7.5/lib/python3.7/json/decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 3 (char 2)
I see, that's my bad I was using the altered version of the input, why are you unable to modify the input?
0

you can try this:

sample="[1abcd245,2bcdasdf,3jakdshfkh234234],[234asdfmnkk234]"
l1 = []
for item in sample.split(","):
    if item.startswith('['):
        l1.append([])
        l1[-1].append(item[1:])
    elif item.endswith(']'):
        l1[-1].append(item[:-2])
    else:
        l1[-1].append(item)


print(l1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.