Python - 限制行数 (numpy)

Python - Limiting number of rows (numpy)

我几乎完成了我的代码。需要你的一点帮助。

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.

所以我需要以某种方式限制 "SUM" 而不限制 "Matrix"

需要得到整个矩阵和每行中所有负数的和,直到第 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

有什么帮助吗?

嗨,我不完全确定你在找什么,但这有用吗?

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 个,然后将这 7 个相加,您的原始矩阵行在 keep_row

中是安全的