正如其他评论者和答案所提到的,对于什么是长度和高度并没有明确的定义。这一切都归结为测量多维数组的维度。
size_of_the_first_dimension = len(p) # length?
size_of_the_second_dimension = max([len(a) for a in p]) # height?
size_of_the_third_dimension = max([len(b) for a in p for b in a]) # depth?
size_of_the_fourth_dimension = max([len(c) for a in p for b in a for c in b]) # colour?
...等等
一般而言,您可以通过如下函数测量第 n 个维度:
def measure(dimension,matrix,aggregator=max):
if dimension <= 0:
raise ValueError('dimension must be greater than 0')
elif dimension == 1:
return aggregator([len(x) for x in [matrix]])
else:
try:
return aggregator([measure(dimension-1,x) for x in matrix])
except TypeError:
raise TypeError('matrix is not uniform or does not have %s dimensions' % dimension)
>>> measure(3,[[[1,2],[],[4]],[[3,4,5]],[[3,2],[],[1,2,3,4,5]],[[]]])
5
如果您对维度大小的定义不同,您可以使用 min 或其他东西(作为第三个参数传入)而不是 max。