在 Python 中获取元组维度

问题描述

Python 3.9.1 64 位

我需要找到传递给函数元组的维度。元组的维度未知,但可以是一维或二维。元组可以采用以下形式:

一维,从 1 个元素到 n 个,示例。

(6,)
(1,4,15,34)
...
(3,56,102,...,n)

二维示例。

((6,),(13,))
((1,34),(203,7,32,9))
...
((3,n),(84,42,(x,y,z,n))

对于二维元组元组将始终具有相同的列号(即,没有锯齿)。

我要强调的是,元组的维度在传递给函数未知函数必须找到它们。我的尝试:

from typing import Tuple

def matrix_dimensions(vector_matrix: tuple)->Tuple[int,int]:
    '''
    given either a one or two dimensional tuple,will determine 
    the dimensions of the tuple.

    parameters:
        vector_matrix: tuple
        either a one or two dimension tuple

    return:
        Tuple[int,int]
        number of rows,and columns as a tuple.

        example:
        (1,4),for a one dim tuple
        (9,5),for a two dim tuple
    '''

    dim_1: int = len(vector_matrix) # this will always work


    # dim_2 will throw an execption if vector_matrix is one dimension,no matter what
    # test I do for it being there or not.

    dim_2: int = len(vector_matrix[0])

    return dim_1,dim_2

dim_1,将始终有效但是,对于 1 暗元组将获得列数,对于 2 暗元组将获得行数。

dim_2,适用于 2 暗元组但是 会抛出异常,对于 1 暗元组

TypeError: object of type 'int' has no len().

我试过测试,vector_matrix[0],对于None,而不是int,是对象,for循环,嵌套for循环,都无济于事。

所以我想我的问题是;

如何测试第二个维度,如果不存在则不抛出异常?

另外,有点背景,将近一年的 Python 编程,来自 ac# 背景,因此为什么我键入定义所有内容,在从 https://data-flair.training/blogs/python-tuple/ 搜索所有元组方法属性后,我看到元组不'没有upper(),也没有lower() 函数,无赖!

谢谢和问候,njc

解决方法

您有多种选择:

捕捉异常

try:
    dim_2 = len(vector_matrix[0])
except TypeError:
    dim_2 = False

检查它是否是 tuple

if isinstance(vector_matrix[0],tuple):
    dim_2 = len(vector_matrix[0])
else:
    dim_2 = False