arrays - 评估列表列表中的行长和维度
问题描述
我需要开发一个函数,它需要两个列表,并在以下情况下生成一个 ValueError:
- 列表的列表具有无与伦比的维度
- 列表中的行长度不同
该函数需要在 vanilla 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')
推荐阅读
- python - 如何使用 binned_statistic 计算非零值
- php - 在 laravel 5.6 api 中按名称选择
- c# - 从具有强类型的特定控制器获取特定操作的路由列表
- ios - 在 iOS 中保存和查看文件
- c - 每次运行时用户定义的减少不返回预期结果
- php - 对手动生成的关联数组进行数组搜索(不同的列名)
- java - 使用机器人类从 Windows 弹出窗口上传文件失败
- laravel - 如何在 Laravel 中映射像 url 'day and name' 这样的 url?
- javascript - 比较对象时遍历文档树的原生 JavaScript 方法
- java - JProfiler Heap Walker - 选择由位于特定 Java 包中的 GC Root 持有的对象