Python 程序打印数组中位于奇数位置的元素

编写一个 Python 程序来打印数组中位于奇数位置或奇数索引位置的元素。在此示例中,列表切片从 0 开始,步长为 2。

import numpy as np

arr = np.array([1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21])

print(arr[0:len(arr):2])
[ 1  5  9 13 17 21]

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

import numpy as np

arr = np.array([10, 25, 20, 33, 40, 55, 60, 77])

print('Printing the Array Elements at Even Position')
for i in range(0, len(arr), 2):
    print(arr[i], end = '  ')
Python Program to Print Array Elements Present on Odd Position

此 Python 程序帮助使用 while 循环打印位于奇数位置的数组元素。 

import numpy as np

odarr = np.array([3, 9, 11, 4, 22, 8, 99, 19, 7])

i = 0
while i < len(odarr):
    print(odarr[i], end = '  ')
    i = i + 2
3  11  22  99  7  

在此 示例 中,if 语句 (if i % 2 == 0) 查找奇数索引位置并打印位于奇数位置的数组元素。 

import numpy as np

odarrlist = []
odarrTot = int(input("Total Array Elements to enter = "))

for i in range(1, odarrTot + 1):
    odarrvalue = int(input("Please enter the %d Array Value = "  %i))
    odarrlist.append(odarrvalue)

odarr = np.array(odarrlist)

print('Printing the Array Elements at Odd Position')
for i in range(0, len(odarr), 2):
    print(odarr[i], end = '  ')

print('\nPrinting the Array Elements at Odd Position')
for i in range(len(odarr)):
    if i % 2 == 0:
        print(odarr[i], end = '  ')
Total Array Elements to enter = 9
Please enter the 1 Array Value = 17
Please enter the 2 Array Value = 22
Please enter the 3 Array Value = 33
Please enter the 4 Array Value = 45
Please enter the 5 Array Value = 56
Please enter the 6 Array Value = 76
Please enter the 7 Array Value = 78
Please enter the 8 Array Value = 89
Please enter the 9 Array Value = 90
Printing the Array Elements at Odd Position
17  33  56  78  90  
Printing the Array Elements at Odd Position
17  33  56  78  90