我几乎完成了我的代码。需要你的帮助。
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))
a = np.array(shape)
for row in a:
neg_sum = sum(row[row < 0]) # sum of negative values
print('{} Sum of Negative Elements In This Row: {}'.format(row, neg_sum))
我需要得到矩阵并且我拥有它,用户输入列和行的数量,并且从这里输入所需的元素数量,我也希望得到每一行中所有负数的总和,这里是输出
How many rows: 3
How many columns: 3
Element: -1
Element: 2
Element: -3
Element: 4
Element: 5
Element: -6
Element: -7
Element: -8
Element: 9
[-1 2 -3] Sum of Negative Elements In This Row: -4
[ 4 5 -6] Sum of Negative Elements In This Row: -6
[-7 -8 9] Sum of Negative Elements In This Row: -15
Press any key to continue . . .
但是我有一个问题,我需要得到每一行中所有负数的总和,直到第7位。现在,如果我制作8x8 9x9或大于7的任何东西,仍然会计算所有矩阵,如果我使用[:7,:]
它在7日结束矩阵并减少其他所有矩阵,即使矩阵是8x8。
所以我需要以某种方式限制&#34; SUM&#34;不限制&#34; Matrix&#34;
需要得到每行中所有负数的整数矩阵和总和,直到7日。
给你一个例子,如果我有矩阵(2x8):
[-1,-1,-1,-1,-1,-1,-1,-1] This gives answer -8
[-1,-1,-1,-1,-1,-1,-1,-1] This gives answer -8
我需要回答:
[-1,-1,-1,-1,-1,-1,-1,-1] This should give -7
[-1,-1,-1,-1,-1,-1,-1,-1] This should give -7
任何帮助?
答案 0 :(得分:0)
嗨,我不完全确定你在寻找什么,但这有用吗?
import numpy as np
import random
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: ")
num = random.randint(-1,1)
A.append(int(num))
shape = np.reshape(A,(n,m))
a = np.array(shape)
for row in a:
keep_row = row
row = row[0:7]
neg_sum = sum(row[row < 0]) # sum of negative values
print('{} Sum of Negative Elements In This Row: {}'.format(keep_row, neg_sum))
它只是从开始到第7个分割数组并加起来七个,你的原始矩阵的行在keep_row中是安全的