Python:2dnumpy数组(矩阵)查找负数(行)的和

2024-09-29 01:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个矩阵(使用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排,即使它会有更多的行,我不感兴趣。在


Tags: of用户inforinputrangeelementsthis
2条回答
a = np.random.random_integers(-1, 1, (10,3))
>>> a
array([[ 0,  0, -1],
       [ 1, -1, -1],
       [ 0,  1,  1],
       [-1,  0,  0],
       [ 1, -1,  0],
       [-1,  1,  1],
       [ 0,  1,  0],
       [ 1, -1,  0],
       [-1,  0,  1],
       [ 1, -1,  1]])
>>>

您可以在任何维度上对numpy数组进行切片。前七行是:

^{pr2}$

在数组上迭代生成可以求和的行。布尔索引可用于根据条件选择项:

>>> for row in a[:7,:]:
...     less_than_zero = row[row < 0]
...     sum_less_than = np.sum(less_than_zero)
...     print('row:{:<14}\tless than zero:{:<11}\tsum:{}'.format(row, less_than_zero, sum_less_than))


row:[ 0  0 -1]      less than zero:[-1]         sum:-1
row:[ 1 -1 -1]      less than zero:[-1 -1]      sum:-2
row:[0 1 1]         less than zero:[]           sum:0
row:[-1  0  0]      less than zero:[-1]         sum:-1
row:[ 1 -1  0]      less than zero:[-1]         sum:-1
row:[-1  1  1]      less than zero:[-1]         sum:-1
row:[0 1 0]         less than zero:[]           sum:0
>>>

遍历二维数组的每一行,用row[row < 0]选择负值,然后计算这些值的总和:

import numpy as np

a = np.array([[-1, 2, -3], [-4, 5, -6], [-7, -8, 9]])  # your array

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))

打印:

^{pr2}$

相关问题 更多 >