您的位置:

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

写一个 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 程序使用 for 循环在偶数索引位置打印列表项。

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

print('Printing the List Items at Even Position')
for i in range(1, len(evList), 2):
    print(evList[i], end = '  ')
Printing the List Items at Even Position
24  48  79  93 

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

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

print('Printing the List Items at Even Position')
i = 1
while i < len(evList):
    print(evList[i], end = '  ')
    i = i + 2
Printing the List Items at Even Position
120  180  60 

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

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