使用 for 循环 range (for i in range(len(negaArr))) 编写一个 Python 程序来打印 Numpy 数组中的负数。if 条件 (if (negaArr[i] < 0)) 找到 numpy 数组项小于零。如果为 True,则打印该负数组项。
# Print Negatives in Array
import numpy as np
negaArr = np.array([11, -22, -33, 14, -17, 12, 0, -9, -34])
print("***The Negative Numbers in this negaArr Array***")
for i in range(len(negaArr)):
if (negaArr[i] < 0):
print(negaArr[i], end = " ")
***The Negative Numbers in this negaArr Array***
-22 -33 -17 -9 -34
使用 for 循环的 Python 程序打印数组中的负数。
在此 Python 示例中,for 循环 (for num in negaArr) 迭代实际的 numpy 数组值。在第二个 for 循环中,numpy 比较函数 (if (np.less(i, 0) == True)) 检查 numpy 数组项是否小于零并返回 True。如果为 True,则从 negaArr numpy 数组中打印该负数。
# Print Negatives in Array
import numpy as np
negaArr = np.array([1, -4, -9, 15, -22, 0, -99, 14, -10, -7, 6])
print("**The Negative Numbers in this negaArr Array***")
for num in negaArr:
if (num < 0):
print(num, end = " ")
print("\n\n=== Using less function===")
print("**The Negative Numbers in this negaArr Array***")
for i in negaArr:
if (np.less(i, 0) == True):
print(i, end = " ")

下面的程序将使用 While 循环返回 Numpy 数组中的负数。
# Print Negative in Array
import numpy as np
negaArr = np.array([1, -34, -77, 11, -90, 88, 65, -17, -30])
i = 0
print("**The Negative Numbers in this negaArr Array***")
while (i < len(negaArr)):
if (np.less(negaArr[i], 0) == True):
print(negaArr[i], end = " ")
i = i + 1
**The Negative Numbers in this negaArr Array***
-34 -77 -90 -17 -30
在此 Python numpy 数组示例中,我们创建了一个 (def printNegativeNumbers(negaArr)) 函数来打印负数。
# Print Negative in Array
import numpy as np
def printNegativeNumbers(negaArr):
for i in negaArr:
if (np.less(i, 0) == True):
print(i, end = " ")
negaArr = np.array([16, -99, -88, 0, -77, 44, -55, -2, 19])
print("**The Negative Numbers in this negaArr Array***")
printNegativeNumbers(negaArr)
**The Negative Numbers in this negaArr Array***
-99 -88 -77 -55 -2