编写一个 Python 程序来打印数组中位于偶数位置或偶数索引位置的元素。在此示例中,我们使用了列表切片,它将以二为步长来打印位于偶数位置的数组元素。
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])
for i in range(1, len(arr), 2):
print(arr[i], end = ' ')
44 88 144 188
此程序有助于使用 while 循环打印位于偶数位置的数组元素。
import numpy as np
arr = np.array([11, 13, 15, 17, 19, 22, 39])
i = 1
while i < len(arr):
print(arr[i], end = ' ')
i = i + 2
13 17 22
在此示例中,我们使用 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