【发布时间】:2018-08-22 15:23:24
【问题描述】:
我在 sublist 上运行递归函数来搜索列表中的元素 check_value 一旦找到它,它会验证 other_value 是否是相应列表的第一项并最终返回索引。但当前代码返回 None。任何人都可以支持,因为我对子列表上的递归函数不太了解。
def check_with_list(dd, check_value, other_value=None):
global new_index
for index, h in enumerate(dd):
if isinstance(h, list):
result = check_with_list(h, check_value)
if result is not None:
if other_value:
new = (index,) + result
if len(new) == 2:
if not dd[new[0]][0] == other_value:
result = None
else:
return (index,) + result
elif h == check_value:
return (index,)
# value not found
return None
dd = [
"gcc",
"fcc",
["scc", "jhh", "rrr"],
["www", "rrr", "rrr"],
"mmm",
["qwe", ["ree", "rer", "rrr"], "ere"]
]
dd = check_with_list(dd, "rrr", "ree")
print(dd)
【问题讨论】:
-
你想要的答案是什么?
-
2,2 如果 'scc' 作为 other_value 传递,而 3,1 当 'www' 是 other_value。
-
这需要递归吗?可以有更多级别的子列表吗?
-
是的,还有更多的列表。
-
如果传递 'ree' 作为其他值索引应该是 5,1,2。