Recursive function on sublist returning None

后端 未结 3 1648
太阳男子
太阳男子 2021-01-27 22:03

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 correspondi

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 22:34

    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")
    

    I have removed the not from the line below:

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

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

提交回复
热议问题