使用anytree模块在python中创建动态树
Posted
技术标签:
【中文标题】使用anytree模块在python中创建动态树【英文标题】:Create dynamic tree in python using anytree module 【发布时间】:2019-11-03 09:47:29 【问题描述】:我尝试为 minmax 算法创建一个实现,并且需要创建一个包含所有可能移动的树。在 python 3.7 中使用 anytree 模块创建树,但是当尝试在第一个树级别迭代并构建下一个级别时收到错误。
Traceback (most recent call last):
Hello from the pygame community. https://www.pygame.org/contribute.html
File "C:/Users/User/PycharmProjects/Tema5AI/Main.py", line 217, in <module>
min_max_algorithm(game)
File "C:/Users/User/PycharmProjects/Tema5AI/Main.py", line 209, in min_max_algorithm
new_node = Node((game, i, 0), parent=(pre, fill, node))
File "C:\Users\User\PycharmProjects\Tema5AI\venv\lib\site-packages\anytree\node\node.py", line 66, in __init__
self.parent = parent
File "C:\Users\User\PycharmProjects\Tema5AI\venv\lib\site-packages\anytree\node\nodemixin.py", line 126, in parent
msg = "Parent node %r is not of type 'NodeMixin'." % (value)
TypeError: not all arguments converted during string formatting
我的构建树代码是:
def min_max_algorithm(game):
first_black_move = util.get_all_available_black(game)
root = Node(game)
for i in first_black_move:
node = Node((game, i, 0), parent=root)
for pre, fill, node in RenderTree(root):
first_white_move = util.get_all_available_white(game)
for i in first_white_move:
new_node = Node((game, i, 0), parent=(pre, fill, node))
for pre, fill, node in RenderTree(root):
print("%s%s" % (pre, node.name))
更确切的问题是: 如何通过当前树向节点添加子节点?
以下问题对我没有帮助: How to specify childrens in anytree and print a tree
Read data from a file and create a tree using anytree in python
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
【问题讨论】:
【参考方案1】:该例外具有误导性。我创建了一张票 https://github.com/c0fec0de/anytree/issues/121。
您可以随时添加节点。请确保仅将节点对象设置为父对象或子对象。也许最好使用迭代器而不是渲染函数,即PreOrderIter。请试试这个
def min_max_algorithm(game):
first_black_move = util.get_all_available_black(game)
root = Node(game)
for i in first_black_move:
node = Node((game, i, 0), parent=root)
for n in PreOrderIter(root):
first_white_move = util.get_all_available_white(game)
for i in first_white_move:
new_node = Node((game, i, 0), parent=n)
for pre, fill, node in RenderTree(root):
print("%s%s" % (pre, node.name))
【讨论】:
以上是关于使用anytree模块在python中创建动态树的主要内容,如果未能解决你的问题,请参考以下文章
为啥 Python zipfile 模块在 zip 文件中创建完整路径
在 Spark 中的 EMR 上使用 --py-files 从 .zip 文件(使用 zipfile 包在 python 中创建)导入模块时出现问题