This question already has answers here:
Converting a string representation of a list into an actual list object [duplicate]
(3个答案)
5年前关闭。
我有这个字符串:
num="['1', '9', '7', '6'],['2', '0', '8', '3', '7'],['3', '8', '5', '7', '9', '10', '4']"
我想返回/输出:
[['1', '9', '7', '6'],['2', '0', '8', '3', '7'],['3', '8', '5', '7', '9', '10', '4']]
我如何从那个巨大的字符串中获得这个列表列表?
python大神给出的解决方案
ast.literal_eval
正是这样做的好处。
>>> num="['1', '9', '7', '6'],['2', '0', '8', '3', '7'],['3', '8', '5', '7', '9', '10', '4']"
>>> import ast
>>> list(ast.literal_eval(num))
[['1', '9', '7', '6'], ['2', '0', '8', '3', '7'], ['3', '8', '5', '7', '9', '10', '4']]