递归函数:“ NoneType”对象不可迭代

时间:2018-06-21 15:28:44

标签: python recursion nonetype

我有一个嵌套的字典,

d={
    "A":1, 
    "depth":0, 
    "chain":[
        {
            "A1":0.7, 
            "depth":1,
            "chain":[
                {
                    "A11":0.3,
                    "depth":2,
                    "key2":{"direct":{},"cumulative":{"B":0.3}}, 
                    "chain":[]
                }, 
                {
                    "A12":0.4, 
                    "depth":2,
                    "chain":[
                        {
                            "A121":0.4, 
                            "depth":3, 
                            "key2":{"direct": {}, "cumulative":{"C":0.2, "D": 0.2}}, 
                           "chain": []
                        }]}]},
        {
            "A2":0.3,
            "depth":1,
            "chain":[
                {
                    "A11":0.3, 
                    "depth":2, 
                    "key2":{"direct":{}, "cumulative":{"D":0.3}},
                    "chain":[]
                }]}]}

我想返回一个列表,其中第一个键重复了x次。 x是“链”下元素的数量。在这种情况下,它将返回:

["A", "A", "A1", "A1", "A2", "A12"]

我尝试了以下

def from_nodes(d):
    from_n=[list(d.keys())[0]]*len(d["chain"])
    for x in d["chain"]:
        if x is not None:
            from_n.extend(from_nodes(x))
            return from_n

出现错误

TypeError                                 Traceback (most recent call last)
<ipython-input-196-6233463c604b>in <module>()
----> 1 from_nodes(test2)

<ipython-input-194-5b7ca4b6db75>in from_nodes(d)
  3     for x in d["chain"]:
  4         if x is not None:
----> 5             from_n.extend(from_nodes(x))
  6         return from_n

<ipython-input-194-5b7ca4b6db75> in from_nodes(d)
  3     for x in d["chain"]:
  4         if x is not None:
----> 5             from_n.extend(from_nodes(x))
  6         return from_n

1 个答案:

答案 0 :(得分:1)

正如我在comments中提到的那样,您的错误是return语句的缩进不正确。如果d["chain"]为空或None,则您的函数将为return None implicitly

将功能更改为以下内容:

def from_nodes(d):
    from_n=[list(d.keys())[0]]*len(d["chain"])
    for x in d["chain"]:
        if x is not None:
            from_n.extend(from_nodes(x))
    return from_n

将纠正该错误,并且我的计算机上的结果是:

print(from_nodes(d))
#['A', 'A', 'A1', 'A1', 'depth', 'depth']

哪个与您期望的输出不匹配-这是因为调用.keys()时不能保证获得确定的顺序。

修改功能以获得所需输出的一种方法是创建要忽略的键列表:

def from_nodes(d):
    ignore_keys = {"chain", "depth", "key2"}
    from_n=[list(k for k in d.keys() if k not in ignore_keys)[0]]*len(d["chain"])
    for x in d["chain"]:
        if x is not None:
            from_n.extend(from_nodes(x))
    return from_n

print(from_nodes(d))
#['A', 'A', 'A1', 'A1', 'A12', 'A2']

但是,这只是我在推测您的要求是什么。您需要根据“第一个”键的含义定义正确的条件。