鱼C论坛

 找回密码
 立即注册
查看: 1541|回复: 4

[已解决]将list一层转变为多层嵌套

[复制链接]
发表于 2023-8-13 22:41:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Given the following list, write a Python program to convert it into a nested dictionary of keys called output20.

q20_list = ['John', 'Danise', 'David', 'Kelly']

The expected output of output20 is {'John': {'Danise': {'David': {'Kelly': {}}}}}

做了很久还是不会
最佳答案
2023-8-13 23:21:13
q20_list = ['John', 'Danise', 'David', 'Kelly']

output20 = {}
for i in range(0, len(q20_list)):
    output20 = {q20_list.pop():output20}

不知道还有没有更好的办法。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-8-13 22:41:51 | 显示全部楼层
将list转换为多层嵌套字典

下面是一个Python程序,可以将给定的列表转换为多层嵌套字典:
q20_list = ['John', 'Danise', 'David', 'Kelly']output20 = {}# 逐层嵌套字典current_dict = output20for item in q20_list:    current_dict[item] = {}    current_dict = current_dict[item]print(output20)
输出:
[/code]
{'John': {'Danise': {'David': {'Kelly': {}}}}}
[/code]

希望这个解决方案能帮助到你!如果有任何进一步的问题,请随时提问。

如果回答对你有帮助,请给我一个最佳答案!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-13 22:42:10 | 显示全部楼层
你可以使用递归来解决这个问题。首先,创建一个空的字典,然后从最后一个元素开始,将其作为值与一个空字典作为键组成的键值对添加到字典中。然后,将新创建的字典作为值与前一个元素作为键组成的键值对添加到字典中。重复这个过程,直到添加完所有的元素。最后,返回最终的字典。

下面是实现这个功能的代码:
def list_to_nested_dict(lst):
    nested_dict = {}
    for item in reversed(lst):
        nested_dict = {item: nested_dict}
    return nested_dict

q20_list = ['John', 'Danise', 'David', 'Kelly']
output20 = list_to_nested_dict(q20_list)
print(output20)

这段代码将输出:
{'John': {'Danise': {'David': {'Kelly': {}}}}}

希望能帮到你!如果你有任何疑问,请随时问我。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-13 22:50:37 | 显示全部楼层
q20_list = ['John', 'Danise', 'David', 'Kelly']
output20 = {}
pointer = output20
for k in q20_list:
    pointer[k] = {}
print('The expected output of output20 is', output20)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-13 23:21:13 | 显示全部楼层    本楼为最佳答案   
q20_list = ['John', 'Danise', 'David', 'Kelly']

output20 = {}
for i in range(0, len(q20_list)):
    output20 = {q20_list.pop():output20}

不知道还有没有更好的办法。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 22:49

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表