检查 Python 矩阵中的每一行,并更改每个第三个索引。

huangapple go评论100阅读模式
英文:

Checking every row in a Python matrix and change each third index

问题

我在使用矩阵的练习中遇到了困难:
我需要使每行中的第四个数字成为其他三个数字的和;基本上,我只需要直接更改第二行和第四行,但我不能直接更改它们。

我需要使用“for”循环来检查每一行,并将索引[3]更改为索引0-2的和。

  1. matrix = [
  2. [1, 1, 1, 3],
  3. [2, 2, 2, 7],
  4. [3, 3, 3, 9],
  5. [4, 4, 4, 13]
  6. ]

我知道有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.

  1. matrix = [
  2. [1, 1, 1, 3],
  3. [2, 2, 2, 7],
  4. [3, 3, 3, 9],
  5. [4, 4, 4, 13]
  6. ]

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. 矩阵 = [
  2. [1, 1, 1, 3],
  3. [2, 2, 2, 7],
  4. [3, 3, 3, 9],
  5. [4, 4, 4, 13]
  6. ]
  7. 对于 in 矩阵:
  8. 行[-1] = 总和(行[:-1])
  9. 对于 in 矩阵:
  10. 打印(行)
  11. #[1, 1, 1, 3]
  12. #[2, 2, 2, 6]
  13. #[3, 3, 3, 9]
  14. #[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

  1. matrix = [
  2. [1, 1, 1, 3],
  3. [2, 2, 2, 7],
  4. [3, 3, 3, 9],
  5. [4, 4, 4, 13]
  6. ]
  7. for row in matrix:
  8. row[-1] = sum(row[:-1])
  9. for row in matrix:
  10. print(row)
  11. #[1, 1, 1, 3]
  12. #[2, 2, 2, 6]
  13. #[3, 3, 3, 9]
  14. #[4, 4, 4, 12]

huangapple
  • 本文由 发表于 2023年6月15日 06:14:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定