1

I am reading a file that has list. Below is the input file.

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

Now as you can see there are lists which is read as string character and I am trying to convert it into an actual list. Below is the code I'm using.

_list = list(sys.stdin.readline().strip())
_final_list = []
    for n in _list:
        try:
            n = int(n)
        except ValueError:
            continue
        if isinstance(n, int):
            _final_list.append(n)

Now my code works fine until a number is more than one digit. For example 42 would become 4, 2. Which is not what I want.

My code generates below result.

[1, 2, 3, 4]
[4, 2] <--- FALSE
[1, 1, 2, 3, 5, 8]
[]

What should I do here to accomplish this task without using libraries such as ast

1
  • Why don't you want to use ast? Why are you doing this in the first place? Why not use a built in serialization method like json or pickle? Commented Feb 3, 2020 at 17:32

2 Answers 2

2

you can use ast.literal_eval:

import ast

_final_list = []
for line in _list:
    python_object = ast.literal_eval(line)        
    if isinstance(python_object, list):
        _final_list.extend(python_object)

or you can use regular expression:

import re

_final_list = []
for line in _list:
    my_list = [e.group() for e in re.finditer(r'\d+', line)]
    _final_list.extend(my_list)
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your suggestion! But As I mentioned before, I don't want to use ast.
any reason to not use?
I am sure there is a way to do it without using libraries. I am preparing for a competition and I will not be able to memorize all libraries there are in the competition. I am trying to solve this problem just in python.
For practice wise, I do not want to use it. But to solve the problem, I would've used ast right away
@Khan check now my answer
|
0

I would strip the endings and split by commas.

def str_to_list(s):
    return [int(i) for i in s.strip('][').split(',') if i]

1 Comment

Awesome! This is perfect!

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.