【问题标题】:Recursively build dictionaries from string characters从字符串字符递归构建字典
【发布时间】:2019-06-03 10:26:59
【问题描述】:

我正在研究针对特定数据结构的压缩算法,其中一部分需要将字符串更改为字典,如下所示:

    "abc" => {'a':{'b':{'c':{}}}

这是一组基于单词字母的嵌套字典。

如何在 python 中以递归方式执行此操作?

【问题讨论】:

  • 您的意思可能是{'a':{'b':{'c':{}}}{a:{b:{c:{}}} 将提高 NameError
  • 感谢指出错误,我已经更正了。
  • 您在问题中陈述了“递归”——这是否意味着您需要解决方案才能使用递归?
  • 最好,是的。

标签: python python-2.7 dictionary recursion


【解决方案1】:

您可以将递归与列表切片一起使用:

def to_dict(d):
  return {} if not d else {d[0]:to_dict(d[1:])}

print(to_dict('abc'))

输出:

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

【讨论】:

    【解决方案2】:

    这是使用reduce的解决方案:

    from functools import reduce
    
    seq = 'abc'
    result = reduce(lambda value, key: { key : value }, reversed(seq), {})
    
    print(result)
    

    输出

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

    【讨论】:

      【解决方案3】:

      这是一种方式:

      s = 'abc'
      d = {}
      current = d
      for c in s:
          current = current.setdefault(c, {})
      print(d)
      # {'a': {'b': {'c': {}}}}
      

      【讨论】:

        猜你喜欢
        • 2021-03-24
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多