首页 > 编程知识 正文

Python 程序:打印数组中负数

时间:2023-11-25 09:12:54 阅读:308986 作者:GUBT

编写一个 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 

使用 for 循环打印数组中负数的 Python 程序。

在这个 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("nn=== 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 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。