Python 是一種功能強大的編程語言,提供了多種數據結構來存儲和操作數據。其中,列表、字典、元組和集合是最常用的四種數據結構。本文將通過實例分析這四種數據結構的特點、用法以及它們之間的區別。
列表是 Python 中最常用的數據結構之一,它是一個有序的可變序列,可以存儲任意類型的元素。
# 創建一個列表
fruits = ['apple', 'banana', 'cherry']
# 訪問列表元素
print(fruits[0]) # 輸出: apple
# 修改列表元素
fruits[1] = 'blueberry'
print(fruits) # 輸出: ['apple', 'blueberry', 'cherry']
# 添加元素
fruits.append('orange')
print(fruits) # 輸出: ['apple', 'blueberry', 'cherry', 'orange']
# 刪除元素
fruits.remove('cherry')
print(fruits) # 輸出: ['apple', 'blueberry', 'orange']
字典是一種無序的鍵值對集合,鍵必須是唯一的,而值可以是任意類型。
# 創建一個字典
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 訪問字典元素
print(person['name']) # 輸出: Alice
# 修改字典元素
person['age'] = 26
print(person) # 輸出: {'name': 'Alice', 'age': 26, 'city': 'New York'}
# 添加元素
person['email'] = 'alice@example.com'
print(person) # 輸出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
# 刪除元素
del person['city']
print(person) # 輸出: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
元組是一種有序的不可變序列,通常用于存儲不可修改的數據。
# 創建一個元組
coordinates = (10, 20)
# 訪問元組元素
print(coordinates[0]) # 輸出: 10
# 嘗試修改元組元素(會報錯)
# coordinates[0] = 15 # TypeError: 'tuple' object does not support item assignment
# 元組解包
x, y = coordinates
print(x, y) # 輸出: 10 20
集合是一種無序且不重復的元素集合,通常用于去重和集合運算。
# 創建一個集合
unique_numbers = {1, 2, 3, 4, 5}
# 添加元素
unique_numbers.add(6)
print(unique_numbers) # 輸出: {1, 2, 3, 4, 5, 6}
# 刪除元素
unique_numbers.remove(3)
print(unique_numbers) # 輸出: {1, 2, 4, 5, 6}
# 集合運算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # 輸出: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # 輸出: {3}
通過合理選擇和使用這些數據結構,可以大大提高代碼的效率和可讀性。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。