Python 打印列表中奇数位置的元素

编写一个 Python 程序来打印列表中奇数位置或奇数索引位置的元素。在此示例中,我们使用列表切片,从 0 开始,步长为 2,直到列表末尾。

odList = [2, 4, 7, 11, 14, 22, 19, 90]

print('Printing the List Items at Odd Position')
print(odList[0:len(odList):2])
Python Program to Print List Items at Odd Position

在此程序中,我们使用 for 循环的 range 来迭代列表元素并打印奇数索引位置的列表元素。

odList = [36, 48, 77, 55, 90, 128, 193, 240]

for i in range(0, len(odList), 2):
    print(odList[i], end = '  ')
36  77  90  193 

使用 while 循环打印列表中奇数位置元素的 Python 程序

odList = [14, 35, 78, 90, 120, 67, 98]

i = 0
while i < len(odList):
    print(odList[i], end = '  ')
    i = i + 2
14  78  120  98  

在此奇数位置列表元素示例中,for 循环从 0 迭代到列表长度。if 条件检查索引位置除以二是否等于 0。如果为真,则打印数字。

import numpy as np

odlist = []
odListTot = int(input("Total List Items to enter = "))

for i in range(1, odListTot + 1):
    odListvalue = int(input("Please enter the %d List Item = "  %i))
    odlist.append(odListvalue)


print('\nPrinting the List Items at Odd Position')
for i in range(0, len(odlist), 2):
    print(odlist[i], end = '  ')

print('\nPrinting the List Items at Odd Position')
for i in range(len(odlist)):
    if i % 2 == 0:
        print(odlist[i], end = '  ')
Total List Items to enter = 8
Please enter the 1 List Item = 14
Please enter the 2 List Item = 24
Please enter the 3 List Item = 34
Please enter the 4 List Item = 44
Please enter the 5 List Item = 54
Please enter the 6 List Item = 64
Please enter the 7 List Item = 74
Please enter the 8 List Item = 84

Printing the List Items at Odd Position
14  34  54  74  
Printing the List Items at Odd Position
14  34  54  74