我正在尝试创建一个从嵌套列表中返回最大值的函数? [英] I am trying to make a function which return max from nested list?

查看:52
本文介绍了我正在尝试创建一个从嵌套列表中返回最大值的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个,它对所有东西都很好,但是当我有一个空列表时在给定的列表 (given_list=[[],1,2,3]) 中,它说索引超出范围.有什么帮助吗?

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?

def r_max (given_list):
    largest = given_list[0]
    while type(largest) == type([]):
        largest = largest[0]

    for element in given_list:
        if type(element) == type([]):
            max_of_elem = r_max(element)
            if largest < max_of_elem:
                largest = max_of_elem
        else:                           # element is not a list
            if largest < element:
                largest = element

    return largest

推荐答案

该错误表明您的索引超出范围,示例中的第一个元素就是这种情况.解决方案不是迭代长度为零的列表:

that error indicates your index is out of range, which is the case with the first element of your example. The solution is not to iterate over lists of length zero:

def r_max (given_list):
    largest = given_list[0]
    while type(largest) == type([]):
        largest = largest[0]

    for element in given_list:
        if type(element) == type([]):
            # If the list is empty, skip
            if(len(elemnt) == 0)
                next
            max_of_elem = r_max(element)
            if largest < max_of_elem:
                largest = max_of_elem
        else:                           # element is not a list
            if largest < element:
                largest = element

    return larges

当你在做的时候,你可能想要 assert len(given_list)>0 或类似的东西.

while your at it, you might want to assert len(given_list)>0 or something equivalent.

这篇关于我正在尝试创建一个从嵌套列表中返回最大值的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆