您的位置:

Python 程序:打印偶数位置数组元素

编写一个 Python 程序,打印偶数位置或偶数索引位置的数组元素。在这个 python 示例中,我们使用了递增 2 的列表切片来打印偶数位置的数组元素。

import numpy as np

arr = np.array([2, 4, 6, 8, 12, 14, 16, 18])

print('Printing the Array Elements at Even Position')
print(arr[1:len(arr):2])

使用 for 循环打印偶数索引位置上的数组元素的 Python 程序。

import numpy as np

arr = np.array([22, 44, 66, 88, 122, 144, 166, 188])

print('Printing the Array Elements at Even Position')
for i in range(1, len(arr), 2):
    print(arr[i], end = '  ')
Printing the Array Elements at Even Position
44  88  144  188 

Python 程序,使用 while 循环打印偶数位置的数组元素

import numpy as np

arr = np.array([11, 13, 15, 17, 19, 22, 39])

print('Printing the Array Elements at Even Position')
i = 1
while i < len(arr):
    print(arr[i], end = '  ')
    i = i + 2
Printing the Array Elements at Even Position
13  17  22 

在这个 Python 示例中,我们使用 if 语句来查找偶数索引位置,并打印偶数位置上存在的数组元素。

import numpy as np

evarrlist = []
evarrTot = int(input("Total Array Elements to enter = "))

for i in range(1, evarrTot + 1):
    evarrvalue = int(input("Please enter the %d Array Value = "  %i))
    evarrlist.append(evarrvalue)

evarr = np.array(evarrlist)

print('\nPrinting the Array Elements at Even Position')
for i in range(1, len(evarr), 2):
    print(evarr[i], end = '  ')

print('\nPrinting the Array Elements at Even Position')
for i in range(len(evarr)):
    if i % 2 != 0:
        print(evarr[i], end = '  ')
Total Array Elements to enter = 9
Please enter the 1 Array Value = 22
Please enter the 2 Array Value = 43
Please enter the 3 Array Value = 56
Please enter the 4 Array Value = 23
Please enter the 5 Array Value = 65
Please enter the 6 Array Value = 98
Please enter the 7 Array Value = 56
Please enter the 8 Array Value = 11
Please enter the 9 Array Value = 99

Printing the Array Elements at Even Position
43  23  98  11  
Printing the Array Elements at Even Position
43  23  98  11