Python中怎么遍历元组

在Python中,可以使用for循环来遍历元组。以下是几种常见的遍历元组的方法:

使用for循环遍历元组的每个元素:

my_tuple = (1, 2, 3, 4, 5)
for item in my_tuple:
    print(item)

使用range()函数和len()函数结合遍历元组的索引:

my_tuple = (1, 2, 3, 4, 5)
for i in range(len(my_tuple)):
    print(my_tuple[i])

使用enumerate()函数遍历元组的索引和元素:

my_tuple = (1, 2, 3, 4, 5)
for index, item in enumerate(my_tuple):
    print(index, item)

这些方法可以根据需求选择适合的遍历方式。

阅读剩余
THE END