英文:
Checking every row in a Python matrix and change each third index
问题
我在使用矩阵的练习中遇到了困难:
我需要使每行中的第四个数字成为其他三个数字的和;基本上,我只需要直接更改第二行和第四行,但我不能直接更改它们。
我需要使用“for”循环来检查每一行,并将索引[3]更改为索引0-2的和。
matrix = [
[1, 1, 1, 3],
[2, 2, 2, 7],
[3, 3, 3, 9],
[4, 4, 4, 13]
]
我知道有NumPy之类的库,但我不认为在这个练习中可以使用它。如果你有任何帮助的方法,我将不胜感激!
谢谢!༼ つ ◕_◕ ༽つ
我认为我需要切片矩阵,并使用for循环来检查每一行,并将每一行的最后一个数字更改为其他三个数字的和。我不知道是否可能做到这一点,因为我无法完全做到这一点:(!
英文:
im having difficulties in a exercice using matrix:
I need to make the 4th number in each row a sum of the others 3; Basically i just need to change the second and fourth row but i cant change then directly.
I need to use a "for" loop to check every row and change the index[3] to a sum of the index 0-2.
matrix = [
[1, 1, 1, 3],
[2, 2, 2, 7],
[3, 3, 3, 9],
[4, 4, 4, 13]
]
I know that there is numpy and things like that but i dont think im allowed to use it for this exercise. If you have anyway to help i would be very grateful!
Thanks!! ༼ つ ◕_◕ ༽つ
I think i need to slice the matrix and use the for loop to check every row and change the last number of every row to a sum of the others three. I dont know if this is possible as i cant quite do it :(!
答案1
得分: 0
矩阵 = [
[1, 1, 1, 3],
[2, 2, 2, 7],
[3, 3, 3, 9],
[4, 4, 4, 13]
]
对于 行 in 矩阵:
行[-1] = 总和(行[:-1])
对于 行 in 矩阵:
打印(行)
#[1, 1, 1, 3]
#[2, 2, 2, 6]
#[3, 3, 3, 9]
#[4, 4, 4, 12]
英文:
>use the for loop to check every row and change the last number of every row to a sum of the others three
matrix = [
[1, 1, 1, 3],
[2, 2, 2, 7],
[3, 3, 3, 9],
[4, 4, 4, 13]
]
for row in matrix:
row[-1] = sum(row[:-1])
for row in matrix:
print(row)
#[1, 1, 1, 3]
#[2, 2, 2, 6]
#[3, 3, 3, 9]
#[4, 4, 4, 12]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论