Python 數據類型入門:數字、字串、列表、元組、字典與集合
學習任何編程語言,理解其基礎數據類型 (Basic Data Types) 都是至關重要的一步。Python 提供了多種內建的數據類型,讓你能夠有效地儲存和操作不同種類的資料。這篇文章將帶你逐一認識 Python 中最常用的基礎數據類型。
🔢 數字 (Numbers)
在 Python 中,數字主要分為整數 (Integers) 和浮點數 (Floating-point numbers)。
整數 (Integer - int
)
整數是沒有小數部分的數字,可以是正數、負數或零。
age = 25
count = -10
year = 2025
print(type(age)) # <class 'int'>
整數支援常見的數學運算:
a = 10
b = 3
print(f"加法: {a + b}") # 輸出: 加法: 13
print(f"減法: {a - b}") # 輸出: 減法: 7
print(f"乘法: {a * b}") # 輸出: 乘法: 30
print(f"除法 (結果為浮點數): {a / b}") # 輸出: 除法 (結果為浮點數): 3.333...
print(f"整除 (Floor Division): {a // b}") # 輸出: 整除 (Floor Division): 3
print(f"模數 (取餘數): {a % b}") # 輸出: 模數 (取餘數): 1
print(f"次方: {a ** b}") # 輸出: 次方: 1000
浮點數 (Float - float
)
浮點數是帶有小數部分的数字。
price = 199.99
pi_value = 3.14159
temperature = -5.5
print(type(price)) # <class 'float'>
浮點數同樣支援上述的數學運算。需要注意的是,由於電腦儲存浮點數的方式,有時可能會出現微小的精度問題。
x = 0.1 + 0.1 + 0.1
print(x) # 可能輸出 0.30000000000000004,而非精確的 0.3
📝 字串 (String - str
)
字串是用來表示文本數據的序列,由一系列字符組成。你可以使用單引號 ('
)、雙引號 ("
) 或三引號 ('''
或 """
) 來創建字串。三引號可以用於多行字串。
greeting = "Hello, Python!"
name = 'Alice'
multi_line_string = """這是一個
多行字串範例。"""
print(type(greeting)) # <class 'str'>
字串是 不可變的 (immutable),這意味著一旦創建,就不能修改其內容。
字串常用操作:
- 串接 (Concatenation): 使用
+
號。pythonfirst_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name) # 輸出: John Doe
- 重複 (Repetition): 使用
*
號。pythonline = "-" * 20 print(line) # 輸出: --------------------
- 索引 (Indexing): 獲取單個字符,索引從 0 開始。python
message = "Python" print(message[0]) # 輸出: P print(message[-1]) # 輸出: n (反向索引)
- 切片 (Slicing): 獲取子字串。python
message = "Hello World" print(message[0:5]) # 輸出: Hello (不包含索引 5) print(message[6:]) # 輸出: World print(message[:5]) # 輸出: Hello
- 常用方法:python
text = " python is fun! " print(len(text)) # 輸出: 20 (字串長度) print(text.upper()) # 輸出: PYTHON IS FUN! print(text.lower()) # 輸出: python is fun! print(text.strip()) # 輸出: python is fun! (移除頭尾空格) print(text.find("is")) # 輸出: 9 (尋找子字串首次出現的索引) print(text.replace("fun", "awesome")) # 輸出: python is awesome! words = "one,two,three".split(',') print(words) # 輸出: ['one', 'two', 'three'] (分割字串成列表)
✅ 布林值 (Boolean - bool
)
布林值只有兩個可能的值:True
或 False
。它們通常用於條件判斷和邏輯運算。
is_active = True
is_student = False
print(type(is_active)) # <class 'bool'>
比較運算符 (如 ==
, !=
, >
, <
) 會返回布林值。
print(5 > 3) # 輸出: True
print(10 == 20) # 輸出: False
⛓️ 列表 (List - list
)
列表是一個 有序 (ordered) 且 可變 (mutable) 的集合,可以包含不同數據類型的元素。列表用方括號 []
定義。
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [10, "hello", True, 3.14]
print(type(fruits)) # <class 'list'>
列表常用操作:
- 索引與切片: 與字串類似。python
print(fruits[0]) # 輸出: apple print(fruits[1:3]) # 輸出: ['banana', 'cherry'] fruits[0] = "orange" # 修改元素,因為列表是可變的 print(fruits) # 輸出: ['orange', 'banana', 'cherry']
- 常用方法:python
my_list = [1, 3, 2] my_list.append(4) # 在末尾添加元素: [1, 3, 2, 4] print(my_list) my_list.insert(1, 5) # 在指定索引處插入元素: [1, 5, 3, 2, 4] print(my_list) my_list.remove(3) # 移除第一個匹配的元素: [1, 5, 2, 4] print(my_list) popped_item = my_list.pop() # 移除並返回末尾元素: 4, my_list is now [1, 5, 2] print(popped_item, my_list) my_list.sort() # 原地排序: [1, 2, 5] print(my_list) print(len(my_list)) # 輸出: 3 (列表長度)
🧱 元組 (Tuple - tuple
)
元組與列表類似,也是一個 有序 (ordered) 的集合。但關鍵區別在於元組是 不可變的 (immutable)。元組用圓括號 ()
定義。
point = (10, 20)
colors = ("red", "green", "blue")
single_element_tuple = (5,) # 注意:單個元素的元組需要一個逗號
print(type(point)) # <class 'tuple'>
元組常用操作:
索引與切片: 與列表和字串一樣。
pythonprint(colors[0]) # 輸出: red print(colors[1:]) # 輸出: ('green', 'blue')
由於不可變性,你不能修改元組中的元素:
python# colors[0] = "yellow" # 這會導致 TypeError
為何使用元組?
- 效能: 元組通常比列表佔用更少記憶體,處理速度也可能稍快。
- 不可變性: 當你希望數據集合不被意外修改時,元組是個好選擇(例如,用作字典的鍵)。
- 數據完整性: 代表固定的數據集合,如座標 (x, y)。
🔑 字典 (Dictionary - dict
)
字典是一個 無序 (unordered) (在 Python 3.7+ 版本中是有序的) 的鍵值對 (key-value pair) 集合。每個鍵 (key) 都是唯一的,並且必須是不可變類型(如字串、數字或元組)。值 (value) 可以是任何數據類型。字典用花括號 {}
定義。
student = {
"name": "Peter Chan",
"age": 20,
"major": "Computer Science"
}
empty_dict = {}
print(type(student)) # <class 'dict'>
字典常用操作:
- 存取值: 通過鍵來存取。python
print(student["name"]) # 輸出: Peter Chan print(student.get("age")) # 輸出: 20 (get 方法更安全,如果鍵不存在返回 None)
- 修改和添加:python
student["age"] = 21 # 修改現有鍵的值 student["school"] = "FKU" # 添加新的鍵值對 print(student) # 輸出: {'name': 'Peter Chan', 'age': 21, 'major': 'Computer Science', 'school': 'FKU'}
- 移除鍵值對:python
del student["major"] print(student) # 輸出: {'name': 'Peter Chan', 'age': 21, 'school': 'FKU'} popped_value = student.pop("age") # 移除並返回指定鍵的值 print(popped_value) # 輸出: 21 print(student) # 輸出: {'name': 'Peter Chan', 'school': 'FKU'}
- 常用方法:python
print(student.keys()) # 輸出: dict_keys(['name', 'school']) print(student.values()) # 輸出: dict_values(['Peter Chan', 'FKU']) print(student.items()) # 輸出: dict_items([('name', 'Peter Chan'), ('school', 'FKU')])
🌿 集合 (Set - set
)
集合是一個 無序 (unordered) 且包含 不重複 (unique) 元素的集合。集合主要用於成員測試 (membership testing)、移除重複元素以及進行數學上的集合運算(如聯集、交集、差集等)。集合也用花括號 {}
定義,但如果花括號為空 {}
, 則表示一個空字典;創建空集合需使用 set()
。
numbers_set = {1, 2, 3, 3, 4, 5} # 重複的 3 會被自動移除
print(numbers_set) # 輸出: {1, 2, 3, 4, 5} (順序可能不同)
empty_set = set()
print(type(numbers_set)) # <class 'set'>
集合常用操作:
- 添加和移除元素:python
my_set = {1, 2, 3} my_set.add(4) # 添加元素: {1, 2, 3, 4} print(my_set) my_set.remove(2) # 移除元素: {1, 3, 4} (如果元素不存在會報錯) print(my_set) my_set.discard(5) # 移除元素: {1, 3, 4} (如果元素不存在不會報錯) print(my_set)
- 集合運算:python
set_a = {1, 2, 3, 4} set_b = {3, 4, 5, 6} print(f"聯集 (Union): {set_a | set_b}") # 輸出: {1, 2, 3, 4, 5, 6} print(f"交集 (Intersection): {set_a & set_b}") # 輸出: {3, 4} print(f"差集 (Difference A-B): {set_a - set_b}") # 輸出: {1, 2} print(f"差集 (Difference B-A): {set_b - set_a}") # 輸出: {5, 6} print(f"對稱差集 (Symmetric Diff): {set_a ^ set_b}") # 輸出: {1, 2, 5, 6} (不同時存在於兩集合的元素)
🔍 類型檢查與轉換 (Type Checking and Conversion)
有時你需要檢查變數的數據類型,或在不同類型之間進行轉換。
類型檢查 type()
type()
函數可以返回一個物件的類型。
value = 100
print(type(value)) # <class 'int'>
value = "Hello"
print(type(value)) # <class 'str'>
類型轉換
Python 提供了內建函數來進行類型轉換:
int(x)
: 將 x 轉換為整數。float(x)
: 將 x 轉換為浮點數。str(x)
: 將 x 轉換為字串。list(x)
: 將 x 轉換為列表。tuple(x)
: 將 x 轉換為元組。set(x)
: 將 x 轉換為集合。dict(x)
: 將 x (通常是鍵值對序列) 轉換為字典。
num_str = "123"
num_int = int(num_str)
print(num_int, type(num_int)) # 輸出: 123 <class 'int'>
num_float = float(num_int)
print(num_float, type(num_float)) # 輸出: 123.0 <class 'float'>
num_to_str = str(num_float)
print(num_to_str, type(num_to_str)) # 輸出: "123.0" <class 'str'>
my_tuple = (1, 2, 3)
my_list_from_tuple = list(my_tuple)
print(my_list_from_tuple, type(my_list_from_tuple)) # 輸出: [1, 2, 3] <class 'list'>
my_list_for_set = [1, 2, 2, 3, 4, 4, 4]
my_set_from_list = set(my_list_for_set)
print(my_set_from_list, type(my_set_from_list)) # 輸出: {1, 2, 3, 4} <class 'set'> (順序可能不同)
🎉 總結 (Conclusion)
掌握 Python 的基礎數據類型是編程旅程中的重要基石。數字、字串、布林值、列表、元組、字典和集合各有其特性和適用場景。理解它們的差異,尤其是有序/無序、可變/不可變的特性,將有助於你編寫更有效率和更穩健的 Python 程式碼。
多加練習,嘗試在不同的情境下使用這些數據類型,你將會更熟悉它們的運用!