I am trying to make a function which return max from nested list?

后端 未结 6 1652
无人及你
无人及你 2021-01-24 08:48

I wrote this and its working fine with everything but when I have an empty list in a given list(given_list=[[],1,2,3]) it saying index is out of range. Any help?

6条回答
  •  后悔当初
    2021-01-24 09:34

    This will find the maximum in a list which contains nested lists and ignore string instances.

    A = [2, 4, 6, 8, [[11, 585, "tu"], 100, [9, 7]], 5, 3, "ccc", 1]
    
    def M(L):
    
        # If list is empty, return nothing
        if len(L) == 0:
            return
    
        # If the list size is one, it could be one element or a list
        if len(L) == 1:
    
            # If it's a list, get the maximum out of it
            if isinstance(L[0], list):
                return M(L[0])
            # If it's a string, ignore it
            if isinstance(L[0], str):
                return
            # Else return the value
            else:
                return L[0]
    
        # If the list has more elements, find the maximum
        else:
            return max(M(L[:1]), M(L[1:]))
    
    
    print A
    print M(A)
    

    Padmal's BLOG

提交回复
热议问题