编程语言
首页 > 编程语言> > python – 如何将表示嵌套列表的字符串解析为实际列表?

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.

标签:nested-lists,python,string,parsing,exec
来源: https://codeday.me/bug/20190927/1824384.html