arrays - 评估列表列表中的行的长度和尺寸

标签 arrays python-3.x list error-handling user-defined-functions

我需要开发一个接受两个列表列表的函数,并在以下情况下生成ValueError:

  • 列表列表具有无与伦比的尺寸
  • 列表中的行长度不相同

  • 该函数必须在普通python中,不能使用任何库

    最佳答案

    def evaluateListsDimensions(first, second):
        
        # Compute both row numbers
        firstSize = len(first)
        secondSize = len(second)
        
        # If those do not match raise ValueError
        if firstSize != secondSize:
            raise ValueError
        
        # If the lists have al least 1 row check their dimensions
        elif firstSize != 0:
       
            # All rows have to be the same size
            sizeToMach = len(first[0])
            allSizesFirst = all(len(list)== sizeToMach for list in first)
            
            # Raise ValueError if at least one was not of the correct size
            if not allSizesFirst:
                raise ValueError
            
            # Check the second group of rows
            # This solution is if you want the the size of both lists is the same
            # Otherwise uncomment the next line 
            # sizeToMatch = len(second[0]) 
            allSizesSecond = all(len(list)== sizeToMach for list in second)
            
            # Raise ValueError if at least one was not of the correct size 
            if not allSizesSecond:
                raise ValueError
    
    如果需要,可以使用以下行为ValueError添加自定义消息:
    raise ValueError('List with wrong dimensions')
    

    关于arrays - 评估列表列表中的行的长度和尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63670131/

    相关文章:

    java - 创建任务[]任务数组

    arrays - 查找数组中众多元素之一的复杂性

    c - 命令行参数中某些情况的输出错误

    c# - C# 中的 Array 和 object[] 有什么区别?

    python - 如何更自然地获取更新列表而不使用标志

    python - 列表修改如何在 python 中工作

    java - 迭代对象/列表

    linux - 如何在任何 linux 发行版中找到 python 包名称?

    Python正则表达式查找目录路径(\\\\Location\\Location\\Location)

    python-3.x - 为什么我得到 "IndentationError: expected an indented block"