获取 Python 中的元组维度

Getting tuple dimensions in Python

Python 3.9.1 64 位

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

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

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

二维示例。

((6,), (13,))
((1, 4, 15, 34), (203, 7, 32, 9))
...
((3, 56, 102, ..., n), (84, 42, 0, ..., n), ..., (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],for None,不是int,is object,for循环,嵌套for循环,无济于事。

所以我想我的问题是;

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

此外,一些背景知识,将近一年的编程 Python,来自 c# 背景,因此我输入 define everything 的原因,在从 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