【问题标题】:how to find the height of a list python如何找到列表python的高度
【发布时间】:2012-06-04 04:57:05
【问题描述】:
p = [[0,0],[0,0],[0,0]].

我知道 len(p) 返回列表的宽度,但在这种情况下如何获得列表的高度为 3?

【问题讨论】:

  • 您需要解释一下宽度和高度是什么意思。在您的示例中,len(p) 为 3。
  • python 的一个有趣的方面是,当您有一个列表列表时,不需要每个子列表的长度相同。例如,您可以有 [ [0,0] 、 [0,0] 、 [0] ]。在这种情况下,您需要进行一些额外的检查,以确保您获得了正确的内部列表的长度。
  • @user1050548:最后一条评论听起来更像LOLCODE,而不是 Python。

标签: python list multidimensional-array


【解决方案1】:

没有列表的“高度”之类的东西。您可能的意思是“当我们选择将矩阵表示为列表列表时,矩阵的高度是多少”? (旁注:表示矩阵的方法有很多种。)

你可以拿第一行:

len(p[0])

但如果你有[],你会遇到错误,所以你想要的是:

len(p[0]) if len(p)!=0 else 0

(要记住的其他事项:如果可以接受 Nx0 矩阵表示为 [[],[],[],...]。我会说不。[] 你是如何表示空矩阵的?我会说是的。但是有些库比如numpy选择不同:numpy.matrix([]).tolist()-->[[]]numpy.matrix([[],[],[]])-->matrix([], shape=(3, 0), dtype=float64)。)

【讨论】:

    【解决方案2】:

    正如其他评论者和答案所提到的,对于什么是长度和高度并没有明确的定义。这一切都归结为测量多维数组的维度。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      相关资源
      最近更新 更多