题解 | #牛牛的矩阵相加#

牛牛的矩阵相加

https://www.nowcoder.com/practice/730b90507602412fac90a3f106bfa0cd

# list1 = [[1,2,3],[4,5,6],[7,8,9]]
# n = int(input())
# for out_x in list1:
#     for inn_x in out_x:
#         inn_x *= n
# 列表元素是不可变的,只是提供了索引,因此并不可行!正确的做法是要索引赋值
# print(list1)

list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = int(input(""))

# 直接通过索引对原始列表中的元素进行操作
for out_x in range(len(list1)):
    for inn_x in range(len(list1[out_x])):
        list1[out_x][inn_x] *= n  # 更新原始列表中的元素

print(list1)

[out_x]并不是子列表本身,而是一个包含单个元素out_x的新列表,应该直接使用len(list1[out_x])来获取每个子列表的长度

执行过程

  1. 开始第一个for循环,使用变量out_x从0遍历到len(list1) - 1(在这个例子中是0到2),每次迭代out_x代表list1的索引。第一次迭代:out_x是0,指向list1[0],即[1, 2, 3]。第二次迭代:out_x是1,指向list1[1],即[4, 5, 6]。第三次迭代:out_x是2,指向list1[2],即[7, 8, 9]。
  2. 对于每个out_x,开始第二个for循环,使用变量inn_x从0遍历到len(list1[out_x]) - 1。对于list1[0],inn_x将从0遍历到2。对于list1[1],inn_x将再次从0遍历到2。对于list1[2],inn_x将最后一次从0遍历到2。
  3. 在第二个for循环内部,使用list1[out_x][inn_x] *= n将当前元素乘以n,并更新原列表中的元素。例如,当out_x是0,inn_x是0时,list1[0][0]即1将被乘以n,然后更新为1*n。
全部评论

相关推荐

嵌入式的小白:有道理哈,这种就看能不能捞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务