我目前正在处理一个问题,该问题要求我采用矩阵/嵌套列表,并为该列表的每个元素添加 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
Run Code Online (Sandbox Code Playgroud)
此代码仅适用于完美矩阵。我的问题是,只要行的长度不同,就会出现错误。例如,如果您要输入列表 [[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]]
Run Code Online (Sandbox Code Playgroud)
但是,如果“矩阵”非常大,我建议您使用numpy.