python - 如何将表示嵌套列表的字符串解析为实际列表?

标签 python parsing string exec nested-lists

<分区>

假设我有一个表示一些嵌套列表的字符串,我想将它转换成真实的东西。我可以做到这一点,我认为:

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 - 如何将表示嵌套列表的字符串解析为实际列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1926741/

相关文章:

python - 无法使用 pynetdicom3 访问 PACS

python - PIL : draw transparent text on top of an image

algorithm - 用于立即评估的调车场算法

python - python 解析器库中的月份和日期交换

c - 使用字符字符串的 if 语句 - 无法识别字符串

Python 3 如何从标准输入上的文件生成 md5 哈希?

python - 神经网络 : designing Cost function "not differentiable"/Tensorflow

python - 如何让 Marshmallow-Sqlalchemy 按关联对象字段排序?

javascript - 如何使用 Json 解析正则表达式文本

java - toString 方法有奇怪的不兼容性?