我有一个矩阵(使用numpy
),用户输入行数和列数。当然,根据用户选择的行数/列数,她输入了多少行。在
现在,我需要为第7行下面的每一行找到一个负元素的和,并在精确的行之后输出每行的总和。这是我的代码(即使最后一个代码不起作用)
import numpy as np
A = list()
n = int(input("How many rows: "))
m = int(input("How many columns: "))
for x in range(n):
if n <= 0 or n>10:
print("Out of range")
break
elif m <= 0 or m>10:
print("Out of range")
break
else:
for y in range(m):
num = input("Element: ")
A.append(int(num))
shape = np.reshape(A,(n,m))
for e in range(n < 7):
if e < 0:
print(sum(e))
print(shape)
如果作为用户,我将输入3行3列,我可以得到这样的结果(我将输入一些数字来解释我需要什么):
^{pr2}$我应该得到这样的东西:
[-1, 2, -3] Sum of Negative Elements In This Row (Till 7th) [-4]
[-4, 5, -6] Sum of Negative Elements In This Row (Till 7th) [-10]
[-7, -8, 9] Sum of Negative Elements In This Row (Till 7th) [-15]
也请不要忘记我只需要到第7排,即使它会有更多的行,我不感兴趣。在
您可以在任何维度上对numpy数组进行切片。前七行是:
^{pr2}$在数组上迭代生成可以求和的行。布尔索引可用于根据条件选择项:
遍历二维数组的每一行,用
row[row < 0]
选择负值,然后计算这些值的总和:打印:
^{pr2}$相关问题 更多 >
编程相关推荐