存储程序序列的数据结构 - Python
我正在编写一个软件,以使用标准控制流从用户那里获取命令序列(即用户可以嵌套他想要的命令):
cmd1
cmd2
cmd3
loop.1:
cmd1
cmd2
cmd3
loop.2
cmd1
cmd2
endloop.2
cmd4
cmd5
endloop.1
您是否知道一种在嵌套结构中保持顺序的数据结构?基本上,什么数据结构用于存储任何语言的输入程序?你知道 Python 中的等价物吗?我正在尝试使用 OrderedDict()
但应该有一个更定制的。
I am writing a software to get sequence of commands from user with standard control flow (i.e user can nest his desired commands) :
cmd1
cmd2
cmd3
loop.1:
cmd1
cmd2
cmd3
loop.2
cmd1
cmd2
endloop.2
cmd4
cmd5
endloop.1
Do you happen to know of a data structure which keeps order in nested structures? Basically, what data structure is used for storing an input program in any language? Do you know the equivalent in Python? I am trying to use OrderedDict()
but there should be a more customized one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用(间接)嵌套列表。我假设你有一门
基本命令的课程。创建 for 循环的子类:
Use an (indirectly) nested list. I assume you have a class
for you basic commands. Make a subclass for loops:
您可以使用二叉树。如果你不想在 python 中实现,你可以伪造这样一棵树的有序遍历并将其存储在一个列表中。
You could use a binary tree. If you don't want to implement one in python, you could fake an in-order traversal of such a tree and store it in a list.
它称为抽象语法树(简称 AST)。
这是一棵树,所以它可以被建模为列表列表,但您可能想要使用具有更多结构的东西(取决于您希望 AST 的“类型”)。
我会为每个节点创建一个对象,每个节点都有一个“操作”和零个或多个叶子(即子表达式或子语句)。
对于更严格类型化的结构,除了常见的“块”、“主体”之外的所有内容,叶子的数量都将受到限制(即使用元组),“块”、“主体”只是语句列表,即函数或 if/while/for 主体。 。
It's called an Abstract Syntax Tree (or AST for short).
Which is .. a tree, so it could be modelled as list-of-lists, but you might want to use something with a bit more structure (depends on how "typed" you want your AST to be).
I'd go with having an object for each Node, each having an 'Operation' and zero or more leaves (i.e. sub-expressions or sub-statements).
For a more rigidly typed structure, the # of leaves would be restricted (i.e. use a tuple) for everything except common "blocks", "body" which are just list-of-statements, i.e. function or if/while/for bodies..