子列表上的递归函数返回无 [英] Recursive function on sublist returning None

查看:47
本文介绍了子列表上的递归函数返回无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在子列表上运行递归函数来搜索列表中的元素 check_value 一旦找到它,它会验证 other_value 是否是相应列表的第一项并最终返回索引.但当前代码返回 None.任何人都可以支持,因为我对子列表上的递归函数没有太多了解.

I'm running a recursive function on sublist to search the element check_value in the list once it finds it, it verifies whether other_value is the first item of the corresponding list and finally return the index.But current code is returning None.can anyone please support as I'm not having much understanding on recursive functions functioning on sublists.

 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)

推荐答案

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 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", "rrr", "rrr"], "ere"]
]
dd = check_with_list(dd, "rrr", "ree")

我已经从下面的行中删除了not:

I have removed the not from the line below:

如果不是 dd[new[0]][0] == other_value:

if not dd[new[0]][0] == other_value:

其他一切似乎都很完美.该代码有效并返回 dd 中第一次出现 check_value 的索引.

Everything else seems to be perfect. The code works and returns the index of the 1st occurrence of check_value in dd.

这篇关于子列表上的递归函数返回无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆