我有一个使用NestedDict类的代码:How can I access a deeply nested dictionary using tuples?。“根据@JCash的回答,我有一个完全可行的例子:“
有两件事我想用它来做,这给我带来了麻烦。首先,我想删除其中一个元素,如果该元素的值为零。第二,如果一个元素是一个空字典,因为该字典的所有条目都被删除了,我想删除这个空字典。在
使用上面的类,示例如下:
my_tuple = (0, 1, 0, 0, 0, 1, 0, 0)
d = NestedDict()
print d
d[my_tuple] = 4
print d
#del d[my_tuple]
del d[0][1][0][0][0][1][0][0]
del d[0][1][0][0][0][1][0]
del d[0][1][0][0][0][1]
del d[0][1][0][0][0]
del d[0][1][0][0]
del d[0][1][0]
del d[0][1]
del d[0]
print d
为了摆脱多层嵌套,del的长列表是必要的。注释掉的del语句(它给出一个键错误)是我想要实现的,具有任意长度的元组。在
删除中间层应该不难,一旦我知道如何删除第一个。我已经知道要删除的内容,可以使用以下命令测试空字典:if(dictionary entry)={})
有什么想法吗?在
编辑:输出为:
^{pr2}$
生成了一个函数
deepdelete
,该函数接受一个键列表并递归地删除叶,然后是任何现在为空的分支字典:把你举的字典作为例子:
^{pr2}$输出:
把更有趣的字典和其他分支一起传来:
输出:
相关问题 更多 >
编程相关推荐