如何使用namedtuple在Python中实现树结构

如何使用namedtuple在Python中实现树结构,python,namedtuple,Python,Namedtuple,我有一个关键词,例如友好。它产生了一个子词,例如warm,而从父词,例如friend,降序而来 from collections import namedtuple keyword = 'friendly' childword = 'warm' parentword = 'friend' connect=namedtuple(keyword,'children parents') output = connect([childword],[parentword]) 因此,我可以使用ou

我有一个关键词,例如友好。它产生了一个子词,例如warm,而从父词,例如friend,降序而来

from collections import namedtuple

keyword = 'friendly'
childword = 'warm'
parentword = 'friend'

connect=namedtuple(keyword,'children parents')
output = connect([childword],[parentword])  
因此,我可以使用output.children查看我的nodeword的子项是什么。然而,我真正想做的是打字

friendly.children # instead of output.children

看到孩子的关键词友好。我该怎么做?我对Python完全陌生;我甚至不确定这是否可行

如果要定义树结构,可以使用namedtuple:

from collections import namedtuple

TreeNode = namedtuple('TreeNode', ['word', 'children'])

friend = TreeNode(word='friend', children=[])
friendly = TreeNode(word='friendly', children=[])
warm = TreeNode(word='warm', children=[])

friend.children.append(friendly)
friendly.children.append(warm)

print(friendly.children)
由此得出:

[TreeNode(word='warm', children=[])]
这是一种非常类似C的做事方式;您最好使用存储边关系的单个图形或树数据结构,例如:

children = dict()
children['friend'] = ['friendly']
children['friendly'] = ['warm']

def parents(word):
    ps = []
    for k in children:
        if word in children[k]:
            ps.append(k)
    return ps

print(children['friendly'])
print(parents('friendly'))
这就产生了

['warm']
['friendly']

有一篇关于可用的文章,您可能会发现它很有用。

可能
命名为tuple
的数据结构不适合您尝试执行的操作,但它有点不清楚。通常,对于这样的问题,最好不要问“我该如何使用特定的工具?”以及“这就是我尝试过的,这就是为什么它不起作用;我可以做些什么不同的事情?”因为也许你一开始没有选择正确的工具。因为这是你问题的标题,实际上并不意味着什么有用的东西。例如,如果你试图构建一个树结构,听起来像是这样,那么已经有很多材料在Python中表示树了。我如何在Python中表示树?我想类可能更接近你想要的