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
循环的信息。