串列(List)#

串列(List)是 Python 中最常用的資料結構,可以儲存 有序可重複可修改 的多個元素,元素型別不必相同:

1
2
3
4
5
# 建立串列
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]  # 不同型別也可以
empty = []  # 空串列

存取元素#

索引(Index)#

索引從 0 開始,負數從尾端算起:

1
2
3
4
5
6
7
8
fruits = ["apple", "banana", "cherry", "date"]
#          0         1         2         3
#         -4        -3        -2        -1

print(fruits[0])   # apple
print(fruits[2])   # cherry
print(fruits[-1])  # date(最後一個)
print(fruits[-2])  # cherry(倒數第二個)

切片(Slicing)#

1
2
3
4
5
6
7
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(nums[2:5])    # [2, 3, 4]
print(nums[:4])     # [0, 1, 2, 3]
print(nums[6:])     # [6, 7, 8, 9]
print(nums[::2])    # [0, 2, 4, 6, 8](每隔一個)
print(nums[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0](反轉)

修改串列#

修改元素#

1
2
3
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)  # ['apple', 'mango', 'cherry']

新增元素#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
fruits = ["apple", "banana"]

# append():加到尾端
fruits.append("cherry")
print(fruits)  # ['apple', 'banana', 'cherry']

# insert():插入到指定位置
fruits.insert(1, "mango")
print(fruits)  # ['apple', 'mango', 'banana', 'cherry']

# extend():合併另一個串列
more = ["date", "elderberry"]
fruits.extend(more)
print(fruits)  # ['apple', 'mango', 'banana', 'cherry', 'date', 'elderberry']

# 或用 + 串接(產生新串列)
new_list = fruits + ["fig"]

刪除元素#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fruits = ["apple", "banana", "cherry", "banana"]

# remove():刪除第一個符合的值
fruits.remove("banana")
print(fruits)  # ['apple', 'cherry', 'banana']

# pop():刪除並回傳指定索引的元素(預設最後一個)
last = fruits.pop()
print(last)    # banana
print(fruits)  # ['apple', 'cherry']

# pop(index):刪除指定索引
item = fruits.pop(0)
print(item)    # apple

# del:刪除指定索引或切片
nums = [1, 2, 3, 4, 5]
del nums[2]
print(nums)  # [1, 2, 4, 5]

del nums[1:3]
print(nums)  # [1, 5]

# clear():清空串列
nums.clear()
print(nums)  # []

查詢操作#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fruits = ["apple", "banana", "cherry", "banana"]

# 是否存在
print("banana" in fruits)     # True
print("mango" not in fruits)  # True

# 計數
print(fruits.count("banana"))  # 2

# 找索引(第一個符合的)
print(fruits.index("cherry"))  # 2

# 長度
print(len(fruits))  # 4

排序#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# sort():原地排序(修改原串列)
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# 由大到小
numbers.sort(reverse=True)
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

# sorted():回傳新串列,不修改原串列
original = [3, 1, 4, 1, 5]
new = sorted(original)
print(original)  # [3, 1, 4, 1, 5](不變)
print(new)       # [1, 1, 3, 4, 5]

# 自訂排序規則(用 key)
words = ["banana", "apple", "cherry", "kiwi"]
words.sort(key=len)           # 依長度排序
print(words)  # ['kiwi', 'apple', 'banana', 'cherry']

words.sort(key=lambda w: w[-1])  # 依最後一個字母排序

反轉#

1
2
3
4
5
6
7
nums = [1, 2, 3, 4, 5]

nums.reverse()
print(nums)  # [5, 4, 3, 2, 1]

# 也可以用切片(產生新串列)
reversed_nums = nums[::-1]

複製串列#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
a = [1, 2, 3]

# 直接賦值:兩個變數指向同一個物件
b = a
b.append(4)
print(a)  # [1, 2, 3, 4](a 也被修改了!)

# 淺複製:產生新物件
c = a.copy()        # 方法一
d = list(a)         # 方法二
e = a[:]            # 方法三

c.append(5)
print(a)  # [1, 2, 3, 4](a 不受影響)
print(c)  # [1, 2, 3, 4, 5]

串列推導式#

串列推導式(List Comprehension)是 Python 中用來快速建立新串列的語法,比傳統的 for 迴圈更簡潔。

基本語法結構:

[運算式 for 變數 in 可迭代物件]
[運算式 for 變數 in 可迭代物件 if 條件]

基本形式:對每個元素做運算#

傳統 for 迴圈寫法:

1
2
3
4
squares = []
for x in range(1, 6):
    squares.append(x ** 2)
print(squares)  # [1, 4, 9, 16, 25]

用串列推導式改寫,一行完成:

1
2
squares = [x ** 2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

加入條件:篩選元素#

在後方加上 if 條件,只保留符合條件的元素:

1
2
3
4
5
6
7
# 只取偶數
even = [x for x in range(10) if x % 2 == 0]
print(even)  # [0, 2, 4, 6, 8]

# 只取大於 3 的平方
big_squares = [x ** 2 for x in range(1, 8) if x > 3]
print(big_squares)  # [16, 25, 36, 49]

if-else:依條件改變輸出值#

if-else 放在運算式的位置(迴圈前方),對每個元素選擇不同的輸出。注意兩種 if 的位置不同:

1
2
3
4
5
6
7
8
9
nums = [1, 2, 3, 4, 5, 6]

# if 在後面 → 篩選(只保留偶數)
keep_even   = [x for x in nums if x % 2 == 0]
print(keep_even)   # [2, 4, 6]

# if-else 在前面 → 轉換(每個元素都保留,但奇數變 0)
mark_even   = [x if x % 2 == 0 else 0 for x in nums]
print(mark_even)   # [0, 2, 0, 4, 0, 6]

巢狀推導式:攤平二維串列#

1
2
3
4
5
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# 等同於兩層 for 迴圈:先走 row,再走 row 裡的 num
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

常用內建函式#

sum() / max() / min() / len()#

這四個函式是處理數字串列最常用的工具:

1
2
3
4
5
6
nums = [3, 1, 4, 1, 5, 9, 2, 6]

print(sum(nums))    # 31  → 所有元素相加
print(max(nums))    # 9   → 最大值
print(min(nums))    # 1   → 最小值
print(len(nums))    # 8   → 元素個數

sum() 還可以指定起始值(預設為 0):

1
print(sum(nums, 100))   # 131(從 100 開始累加)

max()min() 也可以搭配 key 指定比較規則:

1
2
3
4
5
words = ["banana", "apple", "kiwi", "cherry"]

print(max(words))              # kiwi(預設依字母序)
print(max(words, key=len))     # banana(依長度取最長)
print(min(words, key=len))     # kiwi(依長度取最短)

sorted() / reversed()#

sorted() 回傳新串列,不修改原串列;reversed() 回傳一個反向迭代器,需要用 list() 轉換才能看到結果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
nums = [3, 1, 4, 1, 5]

new = sorted(nums)               # 升冪,回傳新串列
print(nums)   # [3, 1, 4, 1, 5](原串列不變)
print(new)    # [1, 1, 3, 4, 5]

desc = sorted(nums, reverse=True)
print(desc)   # [5, 4, 3, 1, 1]

rev = list(reversed(nums))
print(rev)    # [5, 1, 4, 1, 3]

enumerate() / zip()#

enumerate() 同時取得索引zip() 把多個串列逐一配對

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
fruits = ["apple", "banana", "cherry"]

# enumerate:常用於需要編號的迴圈
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry

# zip:把兩個串列合併成鍵值對
prices = [30, 15, 25]
for fruit, price in zip(fruits, prices):
    print(f"{fruit}: {price} 元")
# apple: 30 元
# banana: 15 元
# cherry: 25 元

zip()較短的串列為準,多餘的元素會被捨棄:

1
2
3
a = [1, 2, 3, 4]
b = ["x", "y"]
print(list(zip(a, b)))   # [(1, 'x'), (2, 'y')]

any() / all()#

any() 只要有一個元素符合條件就回傳 Trueall() 需要所有元素都符合才回傳 True

1
2
3
4
5
scores = [85, 92, 78, 60, 95]

print(any(s >= 90 for s in scores))   # True(92、95 符合)
print(all(s >= 60 for s in scores))   # True(全部及格)
print(all(s >= 80 for s in scores))   # False(60、78 不符合)

list() 轉換#

list() 可以把其他可迭代物件轉成串列:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 字串 → 串列
chars = list("Python")
print(chars)   # ['P', 'y', 't', 'h', 'o', 'n']

# range → 串列
r = list(range(5))
print(r)       # [0, 1, 2, 3, 4]

# tuple → 串列
t = list((1, 2, 3))
print(t)       # [1, 2, 3]

實戰範例#

去除重複元素#

1
2
3
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(sorted(unique))  # [1, 2, 3, 4]

攤平巢狀串列#

1
2
3
nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for sublist in nested for x in sublist]
print(flat)  # [1, 2, 3, 4, 5, 6]

依條件分成兩組#

1
2
3
4
5
numbers = range(1, 11)
even = [n for n in numbers if n % 2 == 0]
odd = [n for n in numbers if n % 2 != 0]
print(even)  # [2, 4, 6, 8, 10]
print(odd)   # [1, 3, 5, 7, 9]