gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:33 25 4
gpt4 key购买 nike

我目前正在处理一个问题,该问题需要我采用矩阵/嵌套列表,并将该列表的每个元素加 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 中的矩阵对象。

关于python - 如何在 Python 中为矩阵/嵌套列表的每个元素加 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com