2024-04-20 08:23:37 发布
网友
我正在研究一种针对特定数据结构的压缩算法,其中一部分需要将字符串更改为字典,如下所示:
"abc" => {'a':{'b':{'c':{}}}
它是一组基于单词字母的嵌套字典。你知道吗
如何在python中以递归的方式实现这一点?你知道吗
下面是一个使用reduce的解决方案:
from functools import reduce seq = 'abc' result = reduce(lambda value, key: { key : value }, reversed(seq), {}) print(result)
输出
{'a': {'b': {'c': {}}}}
这是一种方法:
s = 'abc' d = {} current = d for c in s: current = current.setdefault(c, {}) print(d) # {'a': {'b': {'c': {}}}}
可以将递归与列表切片结合使用:
def to_dict(d): return {} if not d else {d[0]:to_dict(d[1:])} print(to_dict('abc'))
输出:
下面是一个使用reduce的解决方案:
输出
这是一种方法:
可以将递归与列表切片结合使用:
输出:
相关问题 更多 >
编程相关推荐