编写一个 Python示例,打印奇数位置或奇数索引位置的数组元素。在这个 Python 示例中,列表切片从 0 开始,然后递增 2。
import numpy as np
arr = np.array([1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21])
print('Printing the Array Elements at Odd Position')
print(arr[0:len(arr):2])
Printing the Array Elements at Odd Position
[ 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示例,使用 while 循环打印奇数位置的数组元素。
import numpy as np
odarr = np.array([3, 9, 11, 4, 22, 8, 99, 19, 7])
print('Printing the Array Elements at Odd Position')
i = 0
while i < len(odarr):
print(odarr[i], end = ' ')
i = i + 2
Printing the Array Elements at Odd Position
3 11 22 99 7
在这个 Python 示例中,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
标签: 正则表达式