gpt4 book ai didi

python - python中递归方法的AttributeError

转载 作者:行者123 更新时间:2023-11-28 18:50:29 25 4
gpt4 key购买 nike

我有一个python的递归方法问题,代码是这样的:

class NodeTree(object):
def __init__(self, name, children):
self.name = name
self.children = children

def count(self):
# 1 + i children's nodes
count = 1
for c in self.children:
count += c.count()
return count


def create_tree(d):
N = NodeTree(d['name'], d['children'])
print N.count()

d1 = {'name':'musica', 'children':[{'name':'rock', 'children':[{'name':'origini','children':[]},
{'name':'rock&roll','children':[]},
{'name':'hard rock', 'children':[]}]},
{'name':'jazz', 'children':[{'name':'origini', 'children':[{'name':'1900', 'children':[]}]},
{'name':'ragtime', 'children':[]}, {'name':'swing', 'children':[]}]}]}
tree = create_tree(d1)

错误是这样的:

count += c.count()
AttributeError: 'dict' object has no attribute 'count'

我什么都试过了,但没用。

无论如何,有什么建议吗?谢谢!

最佳答案

那是因为 Python 字典没有 count 方法。

如果我们逐行检查您的代码实际执行的操作,将会有所帮助。

    def count(self):        # 1 + i children's nodes        count = 1        for c in self.children:      ## self.children is a list of dictionaries, so each c is a dictionary            count += c.count()       ## We are getting .count() of c--which is a dictionary        return count

This is because we passed d1['children'] as self.children, which is a list of dictionaries: [<dict>, <dict>, <dict>, ... ].

Rather than count(), what you should do is call len on the dictionary, to get the number of keys it has, thus becoming:

    for c in self.children:
count += len(c)

关于python - python中递归方法的AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13710546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com