在Python中将矩阵元素从str转换为int

2024-09-25 08:39:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将矩阵的元素从str转换为int(在我从文件中读取它们之后)。 我不想使用任何外部库。在

这是我迄今为止制作的,它正在工作,但我对它不满意(不是很像Python):

def str2int(matrix):
    n = 1 
    m = 1 
    if type(matrix) is ListType:
        n = len(matrix)
        if type(matrix[0]) is ListType:
            m = len(matrix[0])
    new_matrix = []
    i = 0 
    while i < n:
        new_matrix.append([])
        j = 0 
        while j < m:
            new_matrix[i].append(int(matrix[i][j]))
            j += 1
        i += 1
    return new_matrix

有更好的主意吗?在

谢谢。在


Tags: newlenreturnifisdeftypematrix