Python - 遍历元组
遍历元组
您可以使用 for 循环遍历元组中的元素。
在我们的Python for 循环章节中了解更多关于for循环的内容。
按索引号循环
您还可以通过引用索引号来循环遍历元组项。
实例
Print all items by referring to their index number:
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 循环章节中了解更多关于while循环的内容。

