使用 Python 列表推導(dǎo)式解決實(shí)際問(wèn)題
列表推導(dǎo)式是 Python 中非常強(qiáng)大且靈活的特性之一,它能夠讓你以一種簡(jiǎn)潔明了的方式創(chuàng)建列表。本文將從基礎(chǔ)到高級(jí)逐步介紹列表推導(dǎo)式的使用方法,并通過(guò)實(shí)際案例幫助你更好地理解和掌握這一技巧。
1. 基本列表推導(dǎo)式
列表推導(dǎo)式的基本語(yǔ)法如下:
new_list = [expression for item in iterable]
這里,expression 是對(duì) item 進(jìn)行操作的表達(dá)式,iterable 是一個(gè)可迭代對(duì)象,如列表、元組、字符串等。
示例 1:生成一個(gè)包含 1 到 10 的平方的列表
squares = [x**2 for x in range(1, 11)]
print(squares) # 輸出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2. 帶條件的列表推導(dǎo)式
你可以在列表推導(dǎo)式中添加條件語(yǔ)句,以便只對(duì)滿足特定條件的元素進(jìn)行操作。
示例 2:生成一個(gè)包含 1 到 10 中偶數(shù)的平方的列表
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # 輸出: [4, 16, 36, 64, 100]
3. 多層嵌套的列表推導(dǎo)式
列表推導(dǎo)式可以嵌套使用,這樣可以處理更復(fù)雜的結(jié)構(gòu)。
示例 3:生成一個(gè)二維列表,其中每個(gè)子列表包含 1 到 3 的平方
nested_list = [[x**2 for x in range(1, 4)] for _ in range(3)]
print(nested_list) # 輸出: [[1, 4, 9], [1, 4, 9], [1, 4, 9]]
4. 使用多個(gè)可迭代對(duì)象
你可以在列表推導(dǎo)式中使用多個(gè)可迭代對(duì)象,這在處理多個(gè)數(shù)據(jù)源時(shí)非常有用。
示例 4:生成一個(gè)列表,包含兩個(gè)列表中所有可能的組合
list1 = [1, 2, 3]
list2 = ['a', 'b']
combinations = [(x, y) for x in list1 for y in list2]
print(combinations) # 輸出: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
5. 使用復(fù)雜表達(dá)式
列表推導(dǎo)式中的表達(dá)式可以非常復(fù)雜,可以包含函數(shù)調(diào)用、條件表達(dá)式等。
示例 5:生成一個(gè)列表,包含字符串列表中每個(gè)字符串的長(zhǎng)度
words = ["apple", "banana", "cherry"]
lengths = [len(word) for word in words]
print(lengths) # 輸出: [5, 6, 6]
6. 高級(jí)技巧:使用列表推導(dǎo)式進(jìn)行數(shù)據(jù)清洗
列表推導(dǎo)式在數(shù)據(jù)清洗中也非常有用,可以幫助你快速過(guò)濾和轉(zhuǎn)換數(shù)據(jù)。
示例 6:去除字符串列表中的空字符串
dirty_data = ["apple", "", "banana", "", "cherry"]
clean_data = [word for word in dirty_data if word != ""]
print(clean_data) # 輸出: ['apple', 'banana', 'cherry']
7. 實(shí)戰(zhàn)案例:處理日志文件
假設(shè)你有一個(gè)日志文件,每行記錄了一個(gè)用戶的訪問(wèn)時(shí)間。你想要提取出所有訪問(wèn)時(shí)間在上午 9 點(diǎn)到 11 點(diǎn)之間的記錄。
日志文件內(nèi)容(log.txt):
2023-10-01 08:30:00 - User1
2023-10-01 09:15:00 - User2
2023-10-01 10:45:00 - User3
2023-10-01 12:00:00 - User4
代碼實(shí)現(xiàn):
# 讀取日志文件
with open('log.txt', 'r') as file:
logs = file.readlines()
# 使用列表推導(dǎo)式提取符合條件的記錄
filtered_logs = [
log.strip() for log in logs
if '09:' <= log[11:13] < '12:'
]
# 打印結(jié)果
for log in filtered_logs:
print(log)
輸出:
2023-10-01 09:15:00 - User2
2023-10-01 10:45:00 - User3
總結(jié)
本文介紹了 Python 列表推導(dǎo)式的基本用法,包括基本列表推導(dǎo)式、帶條件的列表推導(dǎo)式、多層嵌套的列表推導(dǎo)式、使用多個(gè)可迭代對(duì)象、復(fù)雜表達(dá)式以及數(shù)據(jù)清洗中的應(yīng)用。通過(guò)實(shí)際案例,展示了如何使用列表推導(dǎo)式處理日志文件中的數(shù)據(jù)。