+-
python – 如何将表示嵌套列表的字符串解析为实际列表?
参见英文答案 > Convert string representation of list to list                                    16个
假设我有一个代表一些嵌套列表的字符串,我想把它转换成真实的东西.我想,我能做到这一点:

exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"

但是在用户可能提供字符串来执行的环境中,这可能是一个坏主意.有没有人想要一个能够完成同样事情的整洁解析器?

最佳答案
>>> import ast
>>> mylist = ast.literal_eval("['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']")
>>> mylist
['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']

ast.literal_eval:

Safely evaluate an expression node or
a string containing a Python
expression. The string or node
provided may only consist of the
following Python literal structures:
strings, numbers, tuples, lists,
dicts, booleans, and None.

This can be used for safely evaluating
strings containing Python expressions
from untrusted sources without the
need to parse the values oneself.

点击查看更多相关文章

转载注明原文:python – 如何将表示嵌套列表的字符串解析为实际列表? - 乐贴网