[英]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. 我正在尝试读取嵌套列表的字符串表示形式,并将其转换为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 '['
. 输入
[[1],[2]]
,结果是我刚刚输入的字符串,因此,如果我print(l[0])
则结果为'['
。 Any assistance would be appreciated. 任何援助将不胜感激。
eval
is unsafe as it does not run any background checks on the input. eval
不安全,因为它不会对输入内容进行任何后台检查。 Use literal_eval
from built-in module ast
instead. 使用
literal_eval
从内置模块ast
代替。 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. 与您的代码的问题,如@ BRO-语法指出的是,你认为
eval
原地 ,当你做工作eval(l)
l
被修改。 That is not how it works though . 但这不是它的工作方式 。
eval
returns its result and assigns it to result
in your code. eval
返回其结果并赋予它result
在你的代码。 Try doing print(result[0])
instead and you will see. 尝试改为执行
print(result[0])
,您会看到。
You cannot use eval
but exec
. 您不能使用
eval
但可以使用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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.