Python - 迴圈元組
遍歷元組
你可以使用 for
迴圈來遍歷元組中的項。
在我們的 Python For Loops 章節中瞭解更多關於 for
迴圈的資訊。
遍歷索引號
你也可以透過引用索引號來遍歷元組項。
使用 range()
和 len()
函式來建立一個合適的迭代器。
示例
透過引用索引號列印所有項
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple))
print(thistuple[i])
自己動手試一試 »
使用 While 迴圈
你可以使用 while
迴圈來遍歷元組項。
使用 len()
函式確定元組的長度,然後從 0 開始,透過引用索引號在元組項中迴圈。
記住在每次迭代後將索引加 1。
示例
使用 while
迴圈遍歷所有索引號來列印所有項
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple)
print(thistuple[i])
i = i + 1
自己動手試一試 »
在我們的 Python While Loops 章節中瞭解更多關於 while
迴圈的資訊。