Python: 迴圈迭代列表中的特定元素


在本教程中,我們將編寫一個程式來迴圈迭代給定列表中的元素。讓我們看看解決此問題的步驟

  • 初始化列表和索引。
  • 使用len查詢列表的長度。
  • 使用長度迭代列表。
  • 使用index % length查詢元素的索引。
  • 列印元素。
  • 增加索引。

這是一個簡單的迴圈迭代。你可以毫無問題地編寫它。下面讓我們看看程式碼。

示例

 線上演示

# initializing the list and index
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start_index = 5
# finding the length
length = len(alphabets)
# iterating over the list
for i in range(length):
   # finding the index of the current element
   element_index = start_index % length
   # printing the element
   print(alphabets[element_index], end=' ')
# incrementing the index for the next element
start_index += 1

輸出

如果你執行上面的程式碼,那麼你會得到以下結果。

f g h a b c d e

結論

如果你對本教程有任何疑問,請在評論部分提到它們。

更新於: 2020 年 7 月 7 日

1K+ 檢視次數

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告