Python 程序打印列表中偶数位置的项

编写一个 Python 程序来打印列表中偶数位置或偶数索引位置的项。在此偶数位置示例中,列表切片从 1 开始,到列表末尾结束,步长为 2。

evList = [3, 6, 9, 11, 13, 15, 17, 19]

print('Printing the List Items at Even Position')
print(evList[1:len(evList):2])
Python Program to Print List Items at Even Position

下面的程序将使用 for 循环打印列表中偶数索引位置的项。

evList = [17, 24, 36, 48, 55, 79, 82, 93]

for i in range(1, len(evList), 2):
    print(evList[i], end = '  ')
24  48  79  93  

Python 程序使用 while 循环打印列表中偶数位置的项

evList = [90, 120, 240, 180, 80, 60]

i = 1
while i < len(evList):
    print(evList[i], end = '  ')
    i = i + 2
120  180  60 

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

# Python Program to Print List Items at Even Position using for loop
evlist = []
evListTot = int(input("Total List Items to enter = "))

for i in range(1, evListTot + 1):
    evListvalue = int(input("Please enter the %d List Item = "  %i))
    evlist.append(evListvalue)


print('\nPrinting the List Items at Even Position')
for i in range(1, len(evlist), 2):
    print(evlist[i], end = '  ')

print('\nPrinting the List Items at Even Position')
for i in range(len(evlist)):
    if i % 2 != 0:
        print(evlist[i], end = '  ')
Total List Items to enter = 8
Please enter the 1 List Item = 12
Please enter the 2 List Item = 23
Please enter the 3 List Item = 34
Please enter the 4 List Item = 45
Please enter the 5 List Item = 56
Please enter the 6 List Item = 67
Please enter the 7 List Item = 78
Please enter the 8 List Item = 89

Printing the List Items at Even Position
23  45  67  89  
Printing the List Items at Even Position
23  45  67  89