使用递归 Python 创建嵌套字典 [英] Create a nested dictionary using recursion Python

查看:79
本文介绍了使用递归 Python 创建嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力思考递归的工作原理,特别是如何将其分解为子部分并进行处理,同时保持它全部属于一个整体部分(如果有任何意义).

I'm trying to wrap my head around how recursion works, particularly how you can break it down into sub parts and work on that while maintaining that it all belongs to one overall part, if that makes any sense.

例如:如果给我一个像 [1,2,3,4,5] 这样的列表,我想编写一个函数,该函数在字典中连续创建一个字典,其中列表中的每个元素都是键;输出是这样的 - {1:{2:{3:{4:{5:{}}}}}}.

So for example: if I am given a list like [1,2,3,4,5] and I want to write a function that continuously creates a dictionary within a dictionary with each element in the list being the key; the output being like this - {1:{2:{3:{4:{5:{}}}}}}.

我知道它可以用一个简单的 for 循环来完成,但重点是我想了解递归是如何工作的.这是我尝试过的,我知道这可能还很遥远.:(

I know it can be done with a simple for loop but the point is I want to learn how recursion works. Here is what I tried and I know it's probably pretty far off. :(

data = [1,2,3,4,5]
split_order = dict()

def split(data, split_order):
  if len(data) == 0:
      return split_order
  else:
      attr = data[0]
      new_data = data[1:]
      split_order[attr] = dict()
      split_order[attr] = split(new_data, split_order[attr])

推荐答案

要理解递归是很困难的.所以为了让它更简单一些,我简化了代码(我去掉了第二个参数,你不需要它):

To understood recursion is difficult. So to make it a little simpler I simplified the code (I removed the second parameter, you do not need it):

def split(data):
  if len(data) == 0:
      return data #trivial case, we have no element therefore we return empty list
  else: #if we have elements
      first_value = data[0] #we take the first value
      data = {first_value : split(data[1:])} #data[1:] will return a list with every value but the first value
      return data #this is called after the last recursion is called

如果你用 split[1,2,3,4,5] 调用它,它返回 {1: {2: {3: {4: {5: []}}}}}

If you call it with split[1,2,3,4,5] it returns {1: {2: {3: {4: {5: []}}}}}

让我们看看我们有什么.我们有打破递归的部分,这通常被称为锚点(至少在我的语言中).我们只是检查数据是否为空.你也做了那部分.

Let's see what we have. We have the part that breaks the recursion, this is often called the anchor (at least in my language). We simply check if the data is empty. You did that part as well.

第二部分将提取第一个值并调用拆分,但列表较短.通常这部分将处理提供的数据,然后调用自身.如果数据(列表)不断变小,以便在将来的某个时间可以调用锚点,则是有利的.因此,您通常会移除一项或多项.

The second part will extract the first value and call the split but with a shorter list. Usually this part will work on the provided data and then call itself. It is advantageous if the data (list) is constantly getting smaller so that the anchor can be called at some time in the future. So usually you remove one or more items.

如果我们遍历代码,我们可以看到回避调用的内容.如果我们的输入是 [1,2,3] 我们调用:split([1,2,3]) ->split([2,3]) ->拆分([3])->split()只有在最后一次调用完成后,我们才开始返回值(按此顺序):<代码>[] ->{3: []} ->{2: {3: []}} ->{1:{2:{3:[]}}}

If we step trough the code we can see what the recusion is calling. If our input is [1,2,3] we call: split([1,2,3]) -> split([2,3]) -> split([3]) -> split() Only after the last call is done we start to return the values (in this order): [] -> {3: []} -> {2: {3: []}} -> {1: {2: {3: []}}}

这篇关于使用递归 Python 创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆