首页 > 解决方案 > 评估列表列表中的行长和维度

问题描述

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

  1. 列表的列表具有无与伦比的维度
  2. 列表中的行长度不同

该函数需要在 vanilla python 中并且不能使用任何库

标签: arrayspython-3.xlisterror-handlinguser-defined-functions

解决方案


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')

推荐阅读