如何将代表嵌套列表的字符串解析为实际列表? [英] How do I parse a string representing a nested list into an actual list?
问题描述
说我有一个表示一些嵌套列表的字符串,我想将其转换为真实的东西.我认为我可以做到这一点:
Say I have a string representing some nested lists and I want to convert it into the real thing. I could do this, I think:
exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"
但是在用户可能提供执行字符串的环境中,这可能是/将不是一个好主意.有人对完成相同任务的整洁解析器有任何想法吗?
But in an environment where users might be supplying the string to execute this could/would be a bad idea. Does anybody have any ideas for a tidy parser that would accomplish the same thing?
推荐答案
>>> import ast
>>> mylist = ast.literal_eval("['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']")
>>> mylist
['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']
安全地评估表达式节点或 包含Python的字符串 表达.字符串或节点 提供的只能由 以下Python文字结构: 字符串,数字,元组,列表, dicts,booleans和None.
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.
这可用于安全评估 包含Python表达式的字符串 来自不受信任的来源,而没有 需要自己解析值.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
这篇关于如何将代表嵌套列表的字符串解析为实际列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!