目前,我正在创建两个列表并比较它们是否重复。
相反,我想递归地从字典中删除嵌套项
我的问题是,在执行递归时,如何选择一个深度嵌套的项并更改字典?在
当前功能:
def _finditem(obj,key):
if key == 'haha' or key == 'haha1':
global a_list
global b_list
if isinstance(obj,dict):
_finditem(obj['children'],key)
else:
for x in obj:
if x['title'] == 'Bookmarks Menu':
_finditem(x['children'],'haha')
elif x['title'] == 'surf':
_finditem(x['children'],'haha1')
else:
try:
_finditem(x['children'],key)
except:
if key == 'haha':
a_list.append(x['title'])
elif key == 'haha1':
b_list.append(x['title'])
pass
在迭代列表时修改列表:
我使用了一个列表切片,并根据一个测试函数从原来的列表中排除了项。在
list[:]
是整个列表的列表切片语法Explain Python's slice notation
Remove items from a list while iterating
范围:
列表切片也解决了这个问题,因为它修改了原始对象。 不过,我还是向每个函数添加了
^{pr2}$return
s,并向每个递归函数调用添加了assignment
s。因此,分配给的变量从函数中获取返回值,无论返回值的深度如何。在整个文件:
相关问题 更多 >
编程相关推荐