是否有可能把列表变成一个嵌套的密钥*,没有*递归? [英] Is it possible to turn a list into a nested dict of keys *without* recursion?

查看:102
本文介绍了是否有可能把列表变成一个嵌套的密钥*,没有*递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表如下:

  mylist = ['a','b','c' 'd'] 

是否可以从此列表中创建以下dict 而不

  {
'a':{
' b':{
'c':{
'd':{}
}
}
}
}


解决方案

对于简单的情况,简单地迭代和构建,从最后或开始:

  result = {} 
反转(mylist)中的名称:
result = {name:result }

 code> result = current = {} 
在mylist中的名称:
current [name] = {}
current = current [name]

第一个解决方案也可以使用 reduce()

  reduce(lambda res,name:{name:res},revers(mylist),{})


Supposing I had a list as follows:

mylist = ['a','b','c','d']

Is it possible to create, from this list, the following dict without using recursion/a recursive function?

{
  'a': {
    'b': {
      'c': {
        'd': { }
      }
    }
  }
}

解决方案

For the simple case, simply iterate and build, either from the end or the start:

result = {}
for name in reversed(mylist):
    result = {name: result}

or

result = current = {}
for name in mylist:
    current[name] = {}
    current = current[name]

The first solution can also be expressed as a one-liner using reduce():

reduce(lambda res, name: {name: res}, reversed(mylist), {})

这篇关于是否有可能把列表变成一个嵌套的密钥*,没有*递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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