gpt4 book ai didi

python - 仅对 internal_dep 中存在的键值进行递归调用或跳过跳过列表中存在的键值

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:04 24 4
gpt4 key购买 nike

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

最佳答案

我会将 _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']

关于python - 仅对 internal_dep 中存在的键值进行递归调用或跳过跳过列表中存在的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com