How to converting string to list?

SHASHIKUMAR K L :

I have a file and its consist of multiple lists like below

[234,343,234]
[23,45,34,5]
[354,45]
[]
[334,23]

I am trying to read line by line and append to a single list in python.

how to do it?

I tried so far>

with open("pos.txt","r") as filePos:
    pos_lists=filePos.read()
new_list=[]
for i in pos_lists.split("\n"):
    print(type(i)) #it is str i want it as list
    new_list.extend(i)

print(new_list)

thanks in advance

Sayandip Dutta :

You can try these:

>>> from ast import literal_eval
>>> with open(YOURTEXTFILE) as f:
...    final_list = [literal_eval(elem) for elem in f.readlines()]
>>> final_list
[[234, 343, 234], [23, 45, 34, 5], [354, 45], [], [334, 23]]

Or,

>>> from ast import literal_eval
>>> with open(YOURTEXTFILE) as f:
...    final_list = sum(map(literal_eval, s.readlines()), [])
>>> final_list
[234, 343, 234, 23, 45, 34, 5, 354, 45, 334, 23]

Whichever you want.

The same thing can be done with python built-in eval() however, it is not recommended to use eval() on untrusted code, instead use ast.literal_eval() which only works on very limited data types. For more on this, see Using python's eval() vs. ast.literal_eval()?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=3809&siteId=1