正如其他评论者和答案所提到的那样,对长度和高度的定义并没有明确的定义。这一切都归结为测量多维阵列的尺寸。
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。