寫一個 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 程序中,我們使用 for 循環範圍來迭代列表項,並在奇數索引位置列印列表項。
odList = [36, 48, 77, 55, 90, 128, 193, 240]
print('Printing the List Items at Odd Position')
for i in range(0, len(odList), 2):
print(odList[i], end = ' ')
Printing the List Items at Odd Position
36 77 90 193
odList = [14, 35, 78, 90, 120, 67, 98]
print('Printing the List Items at Odd Position')
i = 0
while i < len(odList):
print(odList[i], end = ' ')
i = i + 2
Printing the List Items at Odd Position
14 78 120 98
在本 Python 列表中奇數位置的項目示例中,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
原創文章,作者:D4H5T,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127025.html