2

我有以下代码递归调用 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']
4

1 回答 1

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']
于 2013-04-28T09:52:40.467 回答