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

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

    If you're confident that there will only be one level of nesting in there, you could do something like

    def r_max(lst):
        new_lst = []
        for i in lst:
            try:
                new_lst.extend(i)
            except TypeError:
                new_lst + [i]
        return max(new_lst)
    

    But I'm not in love with that solution - but it might inspire you to come up with something nicer.

    Two things I'd like to highlight about this solution, in contrast to yours:

    1. All the type-checking you're doing (type(largest) == type([]), etc.) isn't considered idiomatic Python. It works, but one of the key points of Python is that it promotes duck typing/EAFP, which means that you should be more concerned with what an object can do (as opposed to what type it is), and that you should just try stuff and recover as opposed to figuring out if you can do it.
    2. Python has a perfectly good "find the largest number in a list" function - max. If you can make your input a non-nested list, then max does the rest for you.

提交回复
热议问题