Recursive function on sublist returning None

后端 未结 3 1647
太阳男子
太阳男子 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:32

    I believe you structured your logic incorrectly, looking for other_value after the opportunity has passed. Here's an alternate way to structure this:

    def check_with_list(structure, check_value, other_value=None):
    
        for index, item in enumerate(structure):
            path = (index,)
    
            if isinstance(item, list):
    
                sub_path = check_with_list(item, check_value, other_value)
    
                if sub_path is not None:
    
                    path += sub_path
    
                    if other_value and check_value in item:
    
                        if item[0] == other_value:
                            return path
                    else:
                        return path
    
            elif item == check_value:
                return path
    
        return None  # value not found
    
    dd = [
        "gcc",
        "fcc",
        ["scc", "jhh", "rrr"],
        ["www", "rrr", "rrr"],
        "mmm",
        ["qwe", ["ree", "rer", "rrr"], "ere"]
    ]
    
    print(check_with_list(dd, "rrr", "ree"))
    

    OUTPUT

    > python3 test.py
    (5, 1, 2)
    >
    

提交回复
热议问题