Python中如何遍歷元組

小億
152
2024-05-10 14:26:50
欄目: 編程語言

在Python中,遍歷元組可以使用for循環(huán)來實(shí)現(xiàn)。例如:

my_tuple = (1, 2, 3, 4, 5)

for item in my_tuple:
    print(item)

這樣就可以遍歷元組中的每個(gè)元素并打印出來。如果需要獲取元素的索引,可以使用enumerate函數(shù)來實(shí)現(xiàn):

my_tuple = (1, 2, 3, 4, 5)

for index, item in enumerate(my_tuple):
    print(index, item)

這樣就可以同時(shí)獲取元素的索引和值進(jìn)行遍歷操作。

0