首页 > 编程知识 正文

Python 程序:打印数组中正数

时间:2023-11-25 09:12:54 阅读:308991 作者:WFAF

编写一个 Python 程序,使用 for 循环范围(或 i in range(len(posArr))打印数组中的正数。if 条件(if (posArr[i] >= 0))检查 numpy 数组项是否大于或等于零。如果为真,则打印正数组项。

# Print Positives in Array

import numpy as np

posArr = np.array([10, -22, -14, 19, 11, -9, 0])

print("**The Positive Numbers in this posArr Array***")
for i in range(len(posArr)):
    if (posArr[i] >= 0):
        print(posArr[i], end = "  ")
**The Positive Numbers in this posArr Array***
10  19  11  0 

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

在这个 Python 示例中,for 循环(posArr 中的 num)迭代原始值。在第二个 for 循环中,numpy greater_equal 函数(if (np.greater_equal(i,0)= True))检查 numpy 数组项是否大于或等于零并返回 True。如果为真,则打印 numpy 数组中的正数。

# Print Positive in Array

import numpy as np

posArr = np.array([1, 22, -99, -4, 14, 11, -10])

print("**The Positive Numbers in this posArr Array***")
for num in posArr:
    if (num >= 0):
        print(num, end = "  ")

print("nn=== Using greater equal function===")
print("**The Positive Numbers in this posArr Array***")
for i in posArr:
    if (np.greater_equal(i, 0) == True):
        print(i, end = "  ")
**The Positive Numbers in this posArr Array***
1  22  14  11  

=== Using greater equal function===
**The Positive Numbers in this posArr Array***
1  22  14  11 

Python 程序使用 while 循环返回 Numpy 数组中的正数。

# Print Positive in Array

import numpy as np

posArr = np.array([4, -5, 22, -9, -48, 11, 14])
i = 0

print("**The Positive Numbers in this posArr Array***")
while (i < len(posArr)):
    if (np.greater_equal(posArr[i], 0) == True):
        print(posArr[i], end = "  ")
    i = i + 1
**The Positive Numbers in this posArr Array***
4  22  11  14 

在这个 Python numpy 数组示例中,我们创建了一个(def printppositivennumbers(posArr))函数来打印正数。

# Print Positive in Array

import numpy as np

def printPositiveNumbers(posArr):
    for i in posArr:
        if (np.greater_equal(i, 0) == True):
            print(i, end = "  ")

posArr = np.array([1, -11, 0, 15, -9, -17, 22, -67, 55])

print("**The Positive Numbers in this posArr Array***")
printPositiveNumbers(posArr)

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