I have a matrix (using numpy), user enters number of rows and columns. After going through some FOR loops, user enters elements, of course depending on what number of rows and columns did he/she has chosen.

我有一个矩阵(使用numpy),用户输入行数和列数。经过一些FOR循环后,用户输入元素,当然取决于他/她选择的行数和列数。

Now I need to find a sum of negative elements for every row below row 7 and output this every row sum, right after the exact row. Here is my code (even though code for this last thing doesn't work)

现在我需要为第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)

If as a user, I will enter 3 rows and 3 columns, I can get something like this (I'll enter some numbers to explain what I need):

如果作为用户,我将输入3行和3列,我可以得到这样的东西(我将输入一些数字来解释我需要的东西):

[-1, 2, -3]
[-4, 5, -6]
[-7, -8, 9]

I should get something like this:

我应该得到这样的东西:

[-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]

Also please don't forget I need it only till row 7, even if it will have more rows, I am not interested in them.

另外请不要忘记我需要它直到第7行,即使它会有更多行,我对它们不感兴趣。

2 个解决方案

#1


0

Go through every row of your 2D array and select the negative values with row[row < 0] and calculate the sum of these values:

遍历2D数组的每一行,并选择行[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))

This prints:

[-1  2 -3] Sum of Negative Elements In This Row: -4
[-4  5 -6] Sum of Negative Elements In This Row: -10
[-7 -8  9] Sum of Negative Elements In This Row: -15

更多相关文章

  1. 嵌入式Linux要学哪些东西?你真的造吗?
  2. Linux源码包里有个scripts文件夹,里面放的东西起什么作用?
  3. 今天看了一整天的汇编语言,真发现语言这东西只是一种思想!
  4. 求一条sql语句:计算两列的差值,以及各个差值占差值总和的比例
  5. fragment 状态保存时怎么执行一些需要在onResume、onPause方法里
  6. jswdk/jsdk/jdk到底分别是什么东西

随机推荐

  1. 自定义Android 标题栏TitleBar布局
  2. eclipse 配置android
  3. android EditText使用指南
  4. [Android] 仿IOS实现自定义Dialog,底部弹
  5. android操作系统默认的图片
  6. 第十周智能手机开发学习笔记
  7. Android 对话框【Dialog】去除白色边框代
  8. android 用UDP做的心跳连接 小示例
  9. android 检测耳机是否插入
  10. TableLayout