kuyoro
2022-06-10 16:20
采纳率: 90.6%
浏览 49

python 1维list怎么转成2维

# 定义一个list
list=['a1', 'a1','a3', 'a4']
# 希望到的以下的格式:
data=[{
            "name": "a1",
            "childrens": [{
                            "name": "a2",
                            "childrens": [{
                                            "name": "a3",
                                            "childrens": [{
                                                            "name": "a4",
                                                        }]
                                        }]
                         }]
        }]

#希望通过递归实现,但想了好久,失败了 T_T
def CreateSubNode(list,i,data=[]):
    i = 0
    for item in list:
        temp = {
                    "name": item,
                    "childrens":[]
                }
    if i < len(list)-1:
        temp["childrens"].append( CreateSubNode(list,i+1,data))
    data.append(temp)
    return data

if __name__ == "__main__":
    CreateSubNode(list,0,[])

怎么改进呢?

3条回答 默认 最新

相关推荐 更多相似问题