CodeGym /Adesua ahorow /Python SELF TW /迴圈遍歷元組的元素

迴圈遍歷元組的元素

Python SELF TW
等級 8 , 課堂 5
開放

14.1 for 迴圈

在 Python 中,遍歷元組的元素通常使用 for 迴圈。這是 最常見的方法,可以輕鬆地訪問每個元組的 元素並為其執行一段程式碼。

for 迴圈

for 迴圈遍歷每個元組元素,將當前元素的值暫時賦予在 for 關鍵字後面指定的變量。例子:


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

你已經有過使用清單和 for 迴圈的經驗,所以讓我們 看一些實際的例子:

例子 1: 元組元素的總和

讓我們看一個例子,其中我們將所有元組元素相加。


my_tuple = (10, 20, 30, 40, 50)
total = 0

for number in my_tuple:
    total += number

print(f"元組元素的總和: {total}")

在這個例子中,我們創建了元組 my_tuple 和變量 total 來存儲 元素的總和。使用 for 迴圈,我們遍歷每個 元組的元素並將其添加到 total。最終得到所有 元組元素的總和。

例子 2: 尋找最大元素

現在來看一個例子,尋找元組中的最大元素。


my_tuple = (5, 17, 23, 11, 2)
max_value = my_tuple[0]

for number in my_tuple:
    if number > max_value:
        max_value = number

print(f"元組中的最大值: {max_value}")

在這個例子中,我們將變量 max_value 初始化為 元組的第一個元素。然後我們遍歷所有元組元素,將每個 元素與當前的最大值進行比較,並在找到 更大的值時更新 max_value

14.2 巢狀元組

元組可以包含其他元組,可以使用 for 迴圈 來遍歷巢狀資料結構。


nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

for inner_tuple in nested_tuple:
    for number in inner_tuple:
        print(number, end=' ')
    print()

在這個例子中,nested_tuple 包含元組。我們使用巢狀的 for 迴圈來遍歷巢狀元組的每個元素。執行結果:


1 2 3 
4 5 6 
7 8 9 

14.3 帶索引的 for 迴圈

就像清單中的元素一樣,元組中的元素也是有索引的,所以可以使用 for 迴圈(結合 range() 函數)來遍歷元組元素。這使得可以使用不僅是元素本身,還有 它們的位置,這在執行更複雜的資料操作時很有用。

索引迭代的基礎

要遍歷帶有元素索引的元組,您可以使用如下代碼:


my_tuple = ('a', 'b', 'c', 'd')
for i in range(len(my_tuple)):
    print(f'index: {i}, Element: {my_tuple[i]}')

使用索引的優勢

使用索引很容易實現需要同時訪問多個元組元素的算法,例如,用於比較當前 元素與前一個或下一個的算法。

例子:


my_tuple = (15, 20, 23, 18, 22, 19, 21)
for i in range(1, len(my_tuple)):
    if my_tuple[i] > my_tuple[i - 1]:  # 比較元素與前一個
        print(f'{my_tuple[i]} is greater than {my_tuple[i - 1]}')

使用索引的 for 迴圈處理資料

假設我們有一個元組,其中包含一週的溫度資料,我們希望 計算平均溫度,排除極端值(最低 和最高溫度)。


temperatures = (15, 20, 23, 18, 22, 19, 21)
sorted_temps = sorted(temperatures)

# 排除第一和最後一個溫度
filtered_temps = sorted_temps[1:-1]

average_temp = sum(filtered_temps) / len(filtered_temps)
print(f"一週的平均溫度(無極端值): {average_temp}")

14.4 使用 enumerate() 函數

在 Python 中,函數 enumerate() 提供了一種方便的 方法來遍歷元組的元素並同時訪問其索引。 當需要在迴圈中處理列表元素的索引和值時,非常有用。

函數 enumerate() 的基礎

函數 enumerate() 將元組包裝成特殊對象並 返回一個迭代器,該迭代器生成一對 元組值,由元素索引和值組成:


my_tuple = ('apple', 'banana', 'cherry')
for index, element in enumerate(my_tuple):
    print(f'index: {index}, Element: {element}')

現在你擁有的不僅是元素,還有它的索引。

enumerate() 的優勢

使用 enumerate() 可以使代碼更具可讀性並 避免手動使用 range(len(…)) 管理索引。這簡化了對列表元素的操作, 例如更改、訪問元素和執行條件檢查。

用法範例

有時需要找到元組中所有包含某個特定值的索引。


my_tuple = (1, 2, 3, 2, 4, 2, 5)
search_value = 2
indices = []

for index, value in enumerate(my_tuple):
    if value == search_value:
        indices.append(index)

print(f"值 {search_value} 出現在索引: {indices}")

此代碼會找到元組中值為 2 的所有索引:


值 2 出現在索引: [1, 3, 5]

基於索引的資料過濾

讓我們看看一個範例,我們在基於索引過濾資料時,只保留 偶數索引的元素。


my_tuple = ('a', 'b', 'c', 'd', 'e', 'f')

filtered_tuple = tuple(value for index, value in enumerate(my_tuple) if index % 2 == 0)
print(f"具有偶數索引元素的元組: {filtered_tuple}")

該代碼創建了一個新的元組,只包含偶數索引的 元素:


具有偶數索引元素的元組: ('a', 'c', 'e')
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION