尝试使用列表推导将字符串列表转换为整数?

0 投票
1 回答
1372 浏览
提问于 2025-04-28 07:05

我正在尝试使用列表推导式将一个包含多个列表的矩阵中的所有值转换为整数。以下是我从一个程序中提取的代码片段,这个程序读取一个文本文件,文件里是用空格分隔的数字行:

def readMatrix(file):
    contents = open(file).read()
    return [item.split() for item in contents.split("\n")]
    return [int(item) for item in contents]

当我在程序的另一个函数中对这些列表进行数学运算时,我遇到了以下问题:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
暂无标签

1 个回答

1

你可能想要这个:

def readMatrix(file):
    with open(file) as contents:
        return [[int(item) for item in line.split()] for line in contents]

撰写回答