Python 入門 (3) - 數據結構

關於 Python 中常用的數據結構:

數據結構是一種組織和存儲數據的方式,數據結構通常包括系列固定的操作,例如插入、刪除、查找。

本文流程:

數據結構:

1. 集合 (set):

集合主要的功能為添加或確認元素是否在其中,例如:

  • add: 將元素加入集合
  • remove: 將元素從集合中刪除
  • in: 確認元素是否存在於集合中

下例我們建立一個 espania_zoo 並依序加入 {"elephante", "tigre", "tigre", "jirafa"},因為 set 會去除重複所以最後僅包含 {"elephante", "tigre", "jirafa"}

# create an empty set
espania_zoo = set()

# add an element
espania_zoo.add("elephante")                       
espania_zoo.add("tigre")

# 重複加入元素
espania_zoo.add("tigre")                           
espania_zoo.add("jirafa")

# 顯示 espania_zoo: {'elephante', 'jirafa', 'tigre'}
print(espania_zoo)

# 使用 in 可以確認項目是否在集合之中
is_jirafa_in_zoo = "jirafa" in espania_zoo
print(f"Is jirafa in the zoo: {is_jirafa_in_zoo}")

# 移除 tigre
espania_zoo.remove("tigre")                        
is_tigre_in_zoo = "tigre" in espania_zoo
print(f"Is tigre in the zoo: {is_tigre_in_zoo}")

另外集合類型在 Python 中通常用來執行數學上的集合操作,例如交集、聯集、差集等。

# 定義兩家動物園的動物
# 我們可以使用 {} 一次將多個元素加入並形成一個集合
espania_zoo = {"elephante", "tigre", "jirafa"}
colombia_zoo = {"tigre", "jirafa"}

# 取得動物園中交集的動物
intersection = espania_zoo.intersection(colombia_zoo)
is_elephante_in_zoo = "elephante" in intersection
print(f"Do both zoos have elephante: {is_elephante_in_zoo}")

2. 元組 (tuple):

在 Python 中,元組是一種有序的不可變序列,它是由一組元素組成的,這些元素可以是不同的數據類型。

  • 我們可以用 () 將元素加入並形成 tuple,tuple 使用逗號將元素分隔
  • tuple 是不可變的,所以建立後無法再新增或刪除元素
  • 透過索引 [位置索引] 可以取得特定位置的值。位置索引從 0 開始,索引值為 0 代表 tuple 的第零個元素。若位置索引的值為負數代表倒著數的意思 (例如: -1 是最後一個)
  • 透過切片 [起始值: 終止值] 可以取得特定範圍的值
# 建立一個 tuple
my_tuple = (1, 2, 3, 'a', 'b', 'c')
print("Original tuple:", my_tuple)

# 取得第零個元素即 1
print("First element:", my_tuple[0])

# 取得倒數第一個元素即 'c'
print("Last element:", my_tuple[-1])

# 取得索引從 2-4 (不包含 5) 的所有元素
print("Slicing tuple:", my_tuple[2:5])

# 查看 my_tuple 中有幾個元素
print("Length of tuple:", len(my_tuple))

3. 列表 (list):

列表 (list)與元組 (tuple)相似,都具有索引, 切片及長度等功能

# 建立一個 list
my_list = [1, 2, 3, 'a', 'b', 'c'] 
print("Original list:", my_list)

# 取得第零個元素即 1
print("First element:", my_list[0])

# 取得倒數第一個元素即 'c'
print("Last element:", my_list[-1])

# 取得索引從 2-4 (不包含 5) 的所有元素
print("Slicing list:", my_list[2:5]) 

# 查看 my_list 中有幾個元素
print("Length of list:", len(my_list))

列表 (list)與元組 (tuple)不同的是,我們可以修改列表中元素的值

# 將第零個元素修改為 10
my_list[0] = 10
print("Modified list:", my_list)

# 將 4 插入至 my_list 的尾端
my_list.append(4)
print("List after appending:", my_list)

4. 字典 (dict):

  • 我們可以透過 {:} 的方式將元素加入並建立字典
  • 字典的元素有 : 號,代表一種對應關係 (例如下面的 'name': 'Alice', 'age': 30)
  • 'name': 'Alice' 中我們稱 'name' 是,'Alice'是該鍵對應的值。鍵-值的好處是可以形成高可讀性的資料結構。
  • 查找字典的方式為 dict[鍵]
  • 更新字典的方式為 dict[鍵] = 新的值
# 建立新的字典
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print("Original dictionary:", my_dict)

# 查找鍵對應的值
print("Name:", my_dict['name'])
print("Age:", my_dict['age'])

# 更新鍵對應的值
my_dict['age'] = 25
print("Modified dictionary:", my_dict)

my_dict['gender'] = 'Female'
print("Dictionary after adding new pair:", my_dict)

# 刪除鍵
del my_dict['city']
print("Dictionary after removing key-value pair:", my_dict)

# 我們可以用 in 確認鍵是否存在
print("Is 'age' a key in the dictionary?", 'age' in my_dict)
print("Is 'city' a key in the dictionary?", 'city' in my_dict)

5. 使用 for-in 進行迭代:

使用 for-in 迴圈進行迭代可以遍歷數據結構中的每個元素。

my_list = [1, 2, 3, 4, 5]
for num in my_list:
    print(num)

my_tuple = ('a', 'b', 'c', 'd', 'e')
for letter in my_tuple:
    print(letter)

在 Python 3.7 之前,字典(dict)和集合(set)都是無序的,意味著它們的元素的順序是不定的。在不同的情況下,可能會以不同的順序迭代它們的元素

my_set = {1, 2, 3, 4, 5}
for num in my_set:
    print(num)

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
for key, value in my_dict.items():
    print(key, ":", value)  

從 Python 3.7 開始,字典(dict)是有序的。


留言

熱門文章