iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

在 Python 中,列表(List)和元組(Tuple)是兩種常見的數據結構,分別用來存儲有序的元素集合。它們之間的主要區別在於,列表是可變的,而元組是不可變的。

壹、列表(List)

一、創建列表

列表使用方括號 [] 來創建,元素之間用逗號分隔。

fruits = ["apple", "banana", "cherry"]
print(fruits)  # 輸出: ['apple', 'banana', 'cherry']

二、訪問列表元素

你可以使用索引來訪問列表中的元素,索引從 0 開始。

print(fruits[0])  # 輸出: apple

三、修改列表元素

由於列表是可變的,因此你可以修改列表中的元素。

fruits[1] = "blueberry"
print(fruits)  # 輸出: ['apple', 'blueberry', 'cherry']

四、添加元素

你可以使用append()方法在列表的末尾添加新元素。

fruits.append("orange")
print(fruits)  # 輸出: ['apple', 'blueberry', 'cherry', 'orange']

也可以使用insert()方法在指定位置插入新元素。

fruits.insert(1, "banana")
print(fruits)  # 輸出: ['apple', 'banana', 'blueberry', 'cherry', 'orange']

五、刪除元素

可以使用remove()方法刪除指定元素,或使用pop()方法根據索引刪除元素。

fruits.remove("blueberry")
print(fruits)  # 輸出: ['apple', 'banana', 'cherry', 'orange']
fruits.pop(1)
print(fruits)  # 輸出: ['apple', 'cherry', 'orange']

六、列表長度

使用len()函數可以獲取列表的長度。

print(len(fruits))  # 輸出: 3

七、列表切片

你可以使用切片操作來獲取列表的子列表。

print(fruits[1:3])  # 輸出: ['cherry', 'orange']

八、列表遍歷

你可以使用for循環來遍歷列表中的元素。

for fruit in fruits:
    print(fruit)

貳、元組(Tuple)

一、創建元組

元組使用小括號 () 來創建,元素之間用逗號分隔。

fruits_tuple = ("apple", "banana", "cherry")
print(fruits_tuple)  # 輸出: ('apple', 'banana', 'cherry')

二、訪問元組元素

你可以像列表一樣使用索引來訪問元組中的元素。

print(fruits_tuple[0])  # 輸出: apple

三、元組的不可變性

元組與列表最大的不同在於,它是不可變的,因此你不能修改元組中的元素。

fruits_tuple[1] = "blueberry"  # 這會導致錯誤,因為元組不可變

四、元組的長度

與列表一樣,你可以使用len()函數來獲取元組的長度。

print(len(fruits_tuple))  # 輸出: 3

五、元組切片

元組的切片操作與列表類似。

print(fruits_tuple[1:3])  # 輸出: ('banana', 'cherry')

六、元組遍歷

你可以使用for循環來遍歷元組中的元素。

for fruit in fruits_tuple:
    print(fruit)

參、列表和元組的區別

可變性:列表是可變的,這意味著你可以修改、添加或刪除列表中的元素。元組是不可變的,創建之後無法修改。
性能:由於元組不可變,所以在某些情況下,元組的性能比列表更好。
用途:列表更適合需要頻繁修改數據的場景,而元組更適合存儲不會改變的數據,如座標或配置常數。

肆、轉換列表和元組

你可以使用 list() 函數將元組轉換為列表,或使用tuple()函數將列表轉換為元組。

fruits_list = list(fruits_tuple)
print(fruits_list)  # 輸出: ['apple', 'banana', 'cherry']
fruits_tuple_again = tuple(fruits_list)
print(fruits_tuple_again)  # 輸出: ('apple', 'banana', 'cherry')

上一篇
第5天:循環結構
下一篇
第7天:字符串操作
系列文
python30天入門學習13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言