如何将矩阵(列表列表)中的所有值增加 n?

2024-04-02

我必须创建一个函数,将矩阵作为参数传递,然后将矩阵中每个项目的值增加n通过使用嵌套循环。

例如,如果我的矩阵是[[8, 9], [4, 6], [7, 2]] and n = 1, 我想要的输出是[[9, 10], [5, 7], [8, 3]]


您可以编写一个简单的函数来迭代列表,以将每个元素增加n像这样:

def increment_by_n(lst, n):
    for i in range(len(lst)):
        for j in range(len(lst[i])):
            lst[i][j] += n
    return lst

关于第4行的解释:lst[i][j] += n,让我们探讨以下内容:

for i in range(len(lst)): # line 2
    # the above means : for i in [0, 1, 2] 
    # because len(lst) = 3 and hence range(3) = [0, 1, 2]
    # we use this to reference lst[i], i.e lst[0] = [8, 9], lst[1] = [5, 7]
    # Note that lst[0][0] = 8, we will use this below!

    for j in range(len(lst[i])): # line 3
       # first, len(lst[0]) = len(lst[8, 9]) = 2
       # range(2) = [0, 1]
       # so the above means: for j in [0, 1]

       lst[i][j] += n # Line 4
       # We are here referencing the i in [0, 1, 2] and j in [0, 1] in order
       # lst[0][0] = 8 and hence, 8 + 1 = 9
       # lst[0][1] = 9 and hence, 9 + 1 = 10
       # lst[1][0] = 5 and hence, 5 + 1 = 6, and so on...

Note这将修改您的初始列表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将矩阵(列表列表)中的所有值增加 n? 的相关文章

随机推荐