我有以下代码以递归方式调用internal_dep中的每个值,是否有一种方法可以将函数调用更改为仅调用internal_dep中的键或跳过对跳过列表中的键的调用?
internal_dep = {'313115': ['313113'], '313117': ['313115'], '313137': ['313136'], '313136': ['313119'], '313119': ['313118'], '313118': ['313117']}
mainlist = ['313137', '317152' , '314449']
skip = ['313113']
def _getdep(item):
local_list, temp_list = [], []
temp_list.extend(internal_dep[item])
local_list.extend(temp_list)
for new_item in temp_list:
local_list.extend(_getdep(new_item))
return local_list
build_dep_list = []
for item in mainlist:
build_dep_list.append(item)
build_dep_list.extend(_getdep(item))
print build_dep_list
错误: -
Traceback (most recent call last):
File "test.py", line 16, in <module>
build_dep_list.extend(_getdep(item))
File "test.py", line 10, in _getdep
local_list.extend(_getdep(new_item))
File "test.py", line 10, in _getdep
local_list.extend(_getdep(new_item))
File "test.py", line 10, in _getdep
local_list.extend(_getdep(new_item))
File "test.py", line 10, in _getdep
local_list.extend(_getdep(new_item))
File "test.py", line 10, in _getdep
local_list.extend(_getdep(new_item))
File "test.py", line 10, in _getdep
local_list.extend(_getdep(new_item))
File "test.py", line 6, in _getdep
temp_list.extend(internal_dep[item])
KeyError: '313113'
EXPECTED OUTPUT:-
['313115', '313113', '313117','313137','313136','313119','313118','313117']
答案 0 :(得分:3)
我会将_getdep函数修改为:
def _getdep(item):
final_dep = []
dep = internal_dep.get(item, [])
final_dep.extend(internal_dep.get(item, []))
for i in [d for d in dep if d not in skip]:
final_dep.extend(_getdep(i))
return final_dep
对于internal_dep.get(item,[])的使用,请参阅:http://docs.python.org/3/library/stdtypes.html#dict.get(它返回internal_dep [item]的值,或者如果没有这样的键,则返回空列表)
输出
['313137', '313136', '313119', '313118', '313117', '313115', '313113', '317152', '314449']