当前分类:300例题>>正文

Python示例:打印数组中偶数

来源:互联网   更新时间:2023年6月25日  

Python 示例

编写一个 Python示例,使用 for 循环范围(对于 i in range(len(evenArr))打印数组中的偶数。if 语句(if (evenArr[i] % 2 == 0))检查每个索引位置的 numpy 数组项是否可被 2 整除。如果为真,则打印该 numpy 数组偶数。

# Print Even in Array
import numpy as np

evenArr = np.array([10, 23, 99, 40, 70, 22, 19])

print("**The List of Even Numbers in this evenArr Array***")
for i in range(len(evenArr)):
    if (evenArr[i] % 2 == 0):
        print(evenArr[i], end = "  ")

在 Python Numpy 数组输出中打印偶数

**The List of Even Numbers in this evenArr Array***
10  40  70  22 

使用 For 循环打印数组中偶数的 Python示例

在这个 Python 示例中,我们使用 numpy mod 和 numpy 余数函数来检查每个可被 2 整除的数组项的余数是否等于零。如果为真,则从 numpy 数组中打印该偶数。

# Print Even in Array
import numpy as np
evenArr = np.array([1, 22, 99, 44, 74, 89, 190])

print("**The List of Even Numbers in this evenArr Array***")
for i in evenArr:
    if (i % 2 == 0):
        print(i, end = "  ")

print("\n\n=== Using mod function===")
print("**The List of Even Numbers in this evenArr Array***")
for i in evenArr:
    if (np.mod(i, 2) == 0):
        print(i, end = "  ")

print("\n\n=== Using remainder function===")
print("**The List of Even Numbers in this evenArr Array***")
for i in evenArr:
    if (np.remainder(i, 2) == 0):
        print(i, end = "  ")

打印 Python Numpy 数组偶数,用于循环输出

**The List of Even Numbers in this evenArr Array***
22  44  74  190  

=== Using mod function===
**The List of Even Numbers in this evenArr Array***
22  44  74  190  

=== Using remainder function===
**The List of Even Numbers in this evenArr Array***
22  44  74  190 

Python示例使用 While 循环返回数组中的偶数。

# Print Even in Array
import numpy as np

evenArr = np.array([44, 15, 22, 19, 148, 17, 140])
i = 0

print("**The List of Even Numbers in this evenArr Array***")
while (i < len(evenArr)):
    if (np.equal(evenArr[i] % 2, 0)):
        print(evenArr[i], end = "  ")
    i = i + 1

使用 while 循环输出在 Python Numpy 数组中打印偶数

**The List of Even Numbers in this evenArr Array***
44  22  148  140 

在这个 Python numpy 数组的例子中,我们创建了一个检查和打印偶数的函数(printEvenNumbers(evenArr))。

# Print Even in Array
import numpy as np

def printEvenNumbers(evenArr):
    for i in evenArr:
        if (np.remainder(i, 2) == 0):
            print(i, end = "  ")

evenArr = np.array([1, 8, 5, 22, 14, 17, 10, 18, 35, 44])
print("**The List of Even Numbers in this evenArr Array***")
printEvenNumbers(evenArr)

本文固定链接:https://6yhj.com/leku-p-4466.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 赚钱