代码之家  ›  专栏  ›  技术社区  ›  the wolf

确保矩阵元素长度的“Python”方法

  •  -1
  • the wolf  · 技术社区  · 12 年前

    给定列表:

    >>> n=4
    >>> LoL=[range(n) for i in range(n)]
    >>> LoL
    [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
    

    这是显而易见的、可以理解的吗, 蟒蛇的 甚至以这种方式保证N×N矩阵:

    >>> len(LoL) == n and {len(l) for l in LoL} == {n}
    True
    

    因此,它将被这样使用:

    if len(matrix) != 4 or {len(l) for l in matrix} != {4}:
            raise ValueError
    

    还有更好的替代习语吗?或者这是可以理解的吗?

    1 回复  |  直到 12 年前
        1
  •  0
  •   user648852 user648852    11 年前

    正如你在评论中所说,尝试/排除可能更好。

    您不仅会捕捉并尝试使用4x4尺寸以外的元素,还会捕捉到传递给您的错误尺寸:

    >>> LoL=[1,2,3,4]
    >>> len(LoL) == n and {len(l) for l in LoL} == {n}
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in <setcomp>
    TypeError: object of type 'int' has no len()
    

    Vs,如果您对将要使用的数据有疑问:

    >>> try: 
    ...    i=LoL[2][2]
    ... except IndexError:
    ...    print 'no bueno...'
    ... 
    no bueno...