解鎖 Python 列表的秘密:高級方法與內置函數
Python 列表是 Python 編程中最常用的數據結構之一。它不僅可以存儲多個元素,還提供了豐富的內置方法和函數來操作這些元素。今天,我們就來深入探討一下 Python 列表的高級方法和內置函數,幫助你更好地掌握這一強大的工具。
1. 列表推導式
列表推導式是一種簡潔的方式來創建列表。它可以在一行代碼中完成復雜的操作,提高代碼的可讀性和效率。
示例:
# 創建一個包含 0 到 9 的平方的列表
squares = [x**2 for x in range(10)]
print(squares) # 輸出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
解釋:
- range(10) 生成從 0 到 9 的整數。
- x**2 計算每個整數的平方。
- [x**2 for x in range(10)] 將每個平方值添加到列表中。
2. 過濾列表
你可以使用條件語句來過濾列表中的元素。
示例:
# 創建一個包含 0 到 9 中偶數的列表
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # 輸出: [0, 2, 4, 6, 8]
解釋:
- if x % 2 == 0 是一個條件語句,只選擇滿足條件的元素。
- [x for x in range(10) if x % 2 == 0] 將滿足條件的元素添加到列表中。
3. 嵌套列表推導式
嵌套列表推導式可以用來處理多維數據。
示例:
# 創建一個 3x3 的矩陣,其中每個元素是其行號和列號的和
matrix = [[i + j for j in range(3)] for i in range(3)]
print(matrix) # 輸出: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
解釋:
- 外層的 for i in range(3) 生成行號。
- 內層的 for j in range(3) 生成列號。
- i + j 計算每個元素的值。
4. enumerate() 函數
enumerate() 函數可以同時獲取列表的索引和值,常用于循環中。
示例:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
輸出:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
解釋:
- enumerate(fruits) 返回一個枚舉對象,包含索引和對應的值。
- for index, fruit in enumerate(fruits) 同時獲取索引和值。
5. zip() 函數
zip() 函數可以將多個列表合并成一個元組列表,常用于并行迭代。
示例:
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"Name: {name}, Age: {age}")
輸出:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
解釋:
- zip(names, ages) 將兩個列表合并成一個元組列表。
- for name, age in zip(names, ages) 同時獲取兩個列表中的元素。
6. sorted() 函數
sorted() 函數可以對列表進行排序,支持自定義排序規則。
示例:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 輸出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# 按字符串長度排序
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=len)
print(sorted_words) # 輸出: ['date', 'apple', 'cherry', 'banana']
解釋:
- sorted(numbers) 對數字列表進行排序。
- sorted(words, key=len) 按字符串長度排序,key=len 指定排序的關鍵字。
7. filter() 函數
filter() 函數可以過濾列表中的元素,返回滿足條件的元素。
示例:
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # 輸出: [2, 4, 6, 8, 10]
解釋:
- is_even(x) 是一個判斷是否為偶數的函數。
- filter(is_even, numbers) 過濾出滿足條件的元素。
- list(filter(is_even, numbers)) 將過濾結果轉換為列表。
8. map() 函數
map() 函數可以對列表中的每個元素應用一個函數,返回一個新的列表。
示例:
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))
print(squared_numbers) # 輸出: [1, 4, 9, 16, 25]
解釋:
- square(x) 是一個計算平方的函數。
- map(square, numbers) 對每個元素應用 square 函數。
- list(map(square, numbers)) 將結果轉換為列表。
9. reduce() 函數
reduce() 函數可以對列表中的元素進行累積操作,通常需要導入 functools 模塊。
示例:
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(add, numbers)
print(sum_of_numbers) # 輸出: 15
解釋:
- add(x, y) 是一個加法函數。
- reduce(add, numbers) 對列表中的元素進行累積加法。
- sum_of_numbers 是累積結果。
實戰案例:統計單詞頻率
假設你有一個文本文件,需要統計每個單詞出現的頻率。我們可以使用 Python 列表和字典來實現這個功能。
示例代碼:
from collections import defaultdict
import re
def count_words(file_path):
word_count = defaultdict(int)
with open(file_path, 'r') as file:
text = file.read().lower() # 讀取文件內容并轉換為小寫
words = re.findall(r'\b\w+\b', text) # 使用正則表達式提取單詞
for word in words:
word_count[word] += 1 # 統計每個單詞的出現次數
return word_count
# 假設有一個名為 'example.txt' 的文件
word_counts = count_words('example.txt')
for word, count in sorted(word_counts.items(), key=lambda item: item[1], reverse=True):
print(f"{word}: {count}")
解釋:
- defaultdict(int) 創建一個默認值為 0 的字典。
- re.findall(r'\b\w+\b', text) 使用正則表達式提取文本中的單詞。
- word_count[word] += 1 統計每個單詞的出現次數。
- sorted(word_counts.items(), key=lambda item: item[1], reverse=True) 按單詞出現次數降序排序。
本文介紹了 Python 列表的高級方法和內置函數,包括列表推導式、過濾、嵌套列表推導式、enumerate()、zip()、sorted()、filter()、map() 和 reduce()。通過實際的代碼示例,我們展示了如何在實際場景中應用這些方法和函數。