简体   繁体   中英

python convert string representation of nested list of integers to nested list of integers

I am trying to read the string representation of a nested list and convert it to a nested list in python. I have tried the following:

l=input("enter nested list")
result=eval(l)

with input [[1],[2]] and result is the string I just entered so that if I print(l[0]) the result is '[' . Any assistance would be appreciated.

eval is unsafe as it does not run any background checks on the input. Use literal_eval from built-in module ast instead. You can write:

from ast import literal_eval as leval

l = '[[1],[2]]'
result = leval(l)
print(result)     # -> [[1], [2]]
print(result[0])  # -> [1]

The problem with your code, as @bro-grammer points out is that you assume that eval works in-place and when you do eval(l) l is modified. That is not how it works though . eval returns its result and assigns it to result in your code. Try doing print(result[0]) instead and you will see.

You cannot use eval but exec . No need to import any module.

l = input("Enter nested list: ")
exec('result = '+l)
print(result)
print(result[0])

Testing:

Enter nested list: [[1],[2]]
[[1], [2]]
[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM