Python 实现递归

一、使用递归的背景

先来看一个☝️接口结构:

这个孩子,他是一个列表,下面有6个元素

展开children下第一个元素[0]看看:

发现[0]除了包含一些字段信息,还包含了children这个字段(喜当爹),同时这个children下包含了2个元素:

展开他的第一个元素,不出所料,也含有children字段(人均有娃)

可以理解为children是个对象,他包含了一些属性,特别的是其中有一个属性与父级children是一模一样的,他包含父级children所有的属性。

比如每个children都包含了一个name字段,我们要拿到所有children里name字段的值,这时候就要用到递归啦~

二、find_children.py

import requests

def find_children(data, elements):
    children_found = []
    for items in data[elements]:
        children_found.append(items['name'])
        if items['children']:
            more_children = find_children(items, elements)
            for item in more_children:
                children_found.append(item)

    return children_found

headers = {'Content-type': 'application/json', xxxxx}
url = "https://xxxxx"
response = requests.get(url=url,headers=headers).json()

node_f = response["data"]["x x x"]["node"]

a = find_children(node_f, 'children')

print(a)

拆分理解:

1.首先import requests库,用它请求并获取接口返回的数据

headers = {'Content-type': 'application/json', xxxxx}
url = "https://xxxxx"
response = requests.get(url=url,headers=headers).json()

2.若children以上还有很多层级,可以缩小数据范围,定位到children的上一层级

 node_f = response["x x x"]["x x x"]["x x x"] # 定位到children的上一层级

3.来看看定义的函数
我们的函数调用:find_children(node_f, 'children')
其中,node_f:json字段
    children:递归对象

def find_children(data, elements): #第一个传参:json字段,第二个传参:“递归”对象
    children_found = [] #定义一个列表,储存数据
    for items in data[elements]:  #结合传参,这里等于 for items in node_f[‘children’],依次循环children下的元素
        children_found.append(items['name']) #并把name存入列表children_found
        if items['children']:  
            more_children = find_children(items, elements)
            for item in more_children:
                children_found.append(item)

    return children_found #留意find_children函数的返回值是children_found列表

 以下这段是实现递归的核心:
  if items['children']:
 items['children']不为None,表示该元素下的children字段还有子类数据值,此时满足if条件,可理解为 if 1。
 items['children']为None,表示该元素下children值为None,没有后续可递归值,此时不满足if条件,可理解为 if 0,不会再执行if下的语句(不会再递归)。

if items['children']:  
    more_children = find_children(items, elements) # more_children接收了find_children函数的返回值结果,所以more_children是一个包含name值的列表
    for item in more_children: # 把此次接收到的more_children列表中的name值加入children_found列表
        children_found.append(item)

至此,每一层级中children的name以及下一层级children的name就都取出来了

希望到这里能帮助大家理解递归的思路,以后根据这个模板直接套用就行

(晚安啦~)

源码参考:https://www.coder4.com/archives/5767

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容