Recursive function on sublist returning None

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

    I made this code that is quite similar to yours: Instead od using lists, I used dictionary to recursively mark where you can find value, then I made same with list + tuples.

    import pprint
    
    
    def check_with_list(dd, check_value):
        my_indexes = {}
        for index, h in enumerate(dd):
            if isinstance(h, list):
                result = check_with_list(h, check_value)
    
                if result is not None:
                    my_indexes[index] = result
            elif h == check_value:
                my_indexes[index] = True
        return my_indexes
    
    
    def check_with_list_2(dd, check_value):
        my_indexes = []
        for index, h in enumerate(dd):
            if isinstance(h, list):
                result = check_with_list_2(h, check_value)
    
                if result is not None:
                    my_indexes.append((index, result))
            elif h == check_value:
                my_indexes.append(index)
        return my_indexes
    
    
    dd = [
        "aaa",
        "bbb",
        ["bbb", "ccc", "bbb"],
        ["bbb", ["ccc", "aaa", "bbb"], "aaa"]
    ]
    
    rv = check_with_list(dd, "bbb")  # (1,2(0,2),3(0,1(2)))
    pprint.pprint(rv)
    rv = check_with_list_2(dd, "bbb")  # (1,2(0,2),3(0,1(2)))
    pprint.pprint(rv)
    

    Returned values

    {1: True, 2: {0: True, 2: True}, 3: {0: True, 1: {2: True}}}
    [1, (2, [0, 2]), (3, [0, (1, [2])])]
    

提交回复
热议问题