我需要开发一个接受两个列表列表的函数,并在以下情况下生成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/