编写一个 Python示例,使用 for 循环范围打印 Numpy 数组中的负数(对于 I in range(len(negarar))。if 条件(if(nega rar[I]< 0))发现 numpy 数组项小于零。如果为真,则打印该负数组项。
# 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
在这个 Python 示例中,for 循环(对于 negaArr 中的 num)迭代实际的 numpy 数组值。在第二个 for 循环中,numpy less 函数(if (np.less(i,0)= True))检查 numpy 数组项是否小于零并返回 True。如果为真,则打印负数数组中的负数。
# 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 = " ")
Python示例使用 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 print negatenumbers(negarar))函数来打印负数。
# 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
标签: 源码