Tuple 元組
元組類似於清單,是任何類型的元素序列,但它們是不可變的,它們以括號表示。
a = (1, 2, 3)
b = ('red', 'green', 'blue')
範例:如果函式一次回傳多個值時,這資料類型就是 Tuple。
範例:
def convert_seconds(seconds):
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
remaining_seconds = seconds - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
result = convert_seconds(5000)
type(result)
# Return: <class 'tuple'>
範例:Tuple 可以將多個不同值對應不同變數名
def convert_seconds(seconds):
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
remaining_seconds = seconds - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
result = convert_seconds(5000)
hours, minutes, seconds = result
print(hours, minutes, seconds)
# Print: 1 23 20