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

后端 未结 6 1703
无人及你
无人及你 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:36

    If the nesting is arbitrarily deep, you first need recursion to untangle it:

    def items(x):
        if isinstance(x, list):
            for it in x:
                for y in items(it): yield y
        else: yield x
    

    Now, max(items(whatever)) will work fine.

    In recent releases of Python 3 you can make this more elegant by changing

            for it in x:
                for y in items(x): yield y
    

    into:

            for it in x: yield from it
    

提交回复
热议问题