Skip to main content
 首页 » 编程设计

python之如何在 Python 中为矩阵/嵌套列表的每个元素加 1

2025年05月04日12luoye11

我目前正在处理一个问题,该问题需要我采用矩阵/嵌套列表,并将该列表的每个元素加 1,然后返回新的修改后的列表。我还必须这样做,以便用户可以输入他们选择的矩阵/嵌套列表。例如,此人会输入: [[1,2,3],[4,5,6]] 程序将返回 [[2,3,4],[5,6,7]] 到目前为止,我有这段代码:

m = int(input("Enter the number of rows: ")) 
matrice = [] 
i=0 
while (i<m): 
    print("Enter the row", i,"(separate each number by a space)") 
    rang = [int(val) for val in input().split()] 
    matrice.append(rang) 
    i = i + 1 
def add(a): 
    res = [] 
    for i in range(len(a)): 
        row=[] 
        for j in range(len(a[0])): 
            row.append(a[i][j]+1) 
        res.append(row) 
return res 

此代码仅适用于完美矩阵。我的问题是,每当行的长度不同时,它就会给我一个错误。例如,如果您要输入列表 [[1,2,3,4],[4,5,6]],它将不起作用。我想知道如何继续做这个问题。另外,如果可能的话,我宁愿不要使用 numpy。预先感谢您的帮助。

请您参考如下方法:

您可以非常简单地使用列表理解来做到这一点:

x = [[1,2,3,4],[4,5,6]] 
[[z+1 for z in y] for y in x] 
# [[2, 3, 4, 5], [5, 6, 7]] 

但是,如果“矩阵”非常大,我建议您使用 numpy 中的矩阵对象。