使用 Python 列表推導(dǎo)式進行條件過濾的 18 個例子
大家好!今天我們要聊一聊Python中的列表推導(dǎo)式(List Comprehensions)。列表推導(dǎo)式是一種簡潔而強大的方式,可以在一行代碼中創(chuàng)建列表,并且可以輕松地添加條件過濾。如果你還不熟悉列表推導(dǎo)式,不用擔(dān)心,我們會從基礎(chǔ)開始,一步步介紹更高級的概念。
1.基本列表推導(dǎo)式
首先,我們來看一個最簡單的列表推導(dǎo)式,它只是將一個列表中的每個元素乘以2。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式
doubled_numbers = [num * 2 for num in numbers]
print(doubled_numbers) # 輸出: [2, 4, 6, 8, 10]# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式
doubled_numbers = [num * 2 for num in numbers]
print(doubled_numbers) # 輸出: [2, 4, 6, 8, 10]# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式
doubled_numbers = [num * 2 for num in numbers]
print(doubled_numbers) # 輸出: [2, 4, 6, 8, 10]
解釋:這里,[num * 2 for num in numbers] 是一個列表推導(dǎo)式,它遍歷 numbers 列表中的每個元素 num,并將每個 num 乘以2,最終生成一個新的列表 doubled_numbers。
22.添加條件過濾
接下來,我們加上一個條件過濾,只保留偶數(shù)。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加條件過濾
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # 輸出: [2, 4]
解釋:這里,if num % 2 == 0 是一個條件過濾,只有當(dāng) num 是偶數(shù)時,才會被包含在新的列表 even_numbers 中。
3.多重條件過濾
我們可以添加多個條件過濾,例如只保留大于2且小于5的數(shù)字。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加多重條件過濾
filtered_numbers = [num for num in numbers if num > 2 and num < 5]
print(filtered_numbers) # 輸出: [3, 4]
解釋:這里,if num > 2 and num < 5 是一個多重條件過濾,只有當(dāng) num 大于2且小于5時,才會被包含在新的列表 filtered_numbers 中。
4.字符串列表的條件過濾
我們也可以對字符串列表進行條件過濾,例如只保留長度大于3的字符串。
# 原始字符串列表
words = ["apple", "banana", "cherry", "date"]
# 列表推導(dǎo)式加條件過濾
long_words = [word for word in words if len(word) > 3]
print(long_words) # 輸出: ['apple', 'banana', 'cherry']
解釋:這里,if len(word) > 3 是一個條件過濾,只有當(dāng) word 的長度大于3時,才會被包含在新的列表 long_words 中。
5.嵌套列表推導(dǎo)式
我們可以嵌套多個列表推導(dǎo)式,例如生成一個二維列表,并過濾掉所有0。
# 原始二維列表
matrix = [[1, 0, 3], [4, 0, 6], [7, 8, 0]]
# 嵌套列表推導(dǎo)式加條件過濾
filtered_matrix = [[num for num in row if num != 0] for row in matrix]
print(filtered_matrix) # 輸出: [[1, 3], [4, 6], [7, 8]]
解釋:這里,外層的列表推導(dǎo)式遍歷 matrix 中的每一行 row,內(nèi)層的列表推導(dǎo)式遍歷 row 中的每個元素 num,并過濾掉所有為0的元素。
6.使用 and 和 or 進行條件過濾
我們可以使用 and 和 or 來組合多個條件,例如只保留大于2或小于4的數(shù)字。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加條件過濾
filtered_numbers = [num for num in numbers if num > 2 or num < 4]
print(filtered_numbers) # 輸出: [1, 2, 3, 5]
解釋:這里,if num > 2 or num < 4 是一個條件過濾,只有當(dāng) num 大于2或小于4時,才會被包含在新的列表 filtered_numbers 中。
7.使用 not 進行條件過濾
我們可以使用 not 來反轉(zhuǎn)條件,例如只保留不是偶數(shù)的數(shù)字。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加條件過濾
odd_numbers = [num for num in numbers if not num % 2 == 0]
print(odd_numbers) # 輸出: [1, 3, 5]
解釋:這里,if not num % 2 == 0 是一個條件過濾,只有當(dāng) num 不是偶數(shù)時,才會被包含在新的列表 odd_numbers 中。
8.使用 in 和 not in 進行條件過濾
我們可以使用 in 和 not in 來檢查元素是否存在于某個集合中,例如只保留存在于另一個列表中的數(shù)字。
# 原始列表
numbers = [1, 2, 3, 4, 5]
allowed_numbers = [2, 4, 6]
# 列表推導(dǎo)式加條件過濾
filtered_numbers = [num for num in numbers if num in allowed_numbers]
print(filtered_numbers) # 輸出: [2, 4]
解釋:這里,if num in allowed_numbers 是一個條件過濾,只有當(dāng) num 存在于 allowed_numbers 中時,才會被包含在新的列表 filtered_numbers 中。
9.使用 lambda 函數(shù)進行條件過濾
我們可以使用 lambda 函數(shù)來定義復(fù)雜的條件,例如只保留平方后大于10的數(shù)字。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加條件過濾
filtered_numbers = [num for num in numbers if (lambda x: x ** 2 > 10)(num)]
print(filtered_numbers) # 輸出: [4, 5]
解釋:這里,(lambda x: x ** 2 > 10)(num) 是一個 lambda 函數(shù),它計算 num 的平方,并檢查是否大于10。只有當(dāng) num 的平方大于10時,才會被包含在新的列表 filtered_numbers 中。
10.使用 enumerate
進行條件過濾 我們可以使用 enumerate 函數(shù)來獲取元素的索引,例如只保留索引為偶數(shù)的元素。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加條件過濾
filtered_numbers = [num for i, num in enumerate(numbers) if i % 2 == 0]
print(filtered_numbers) # 輸出: [1, 3, 5]
解釋:這里,for i, num in enumerate(numbers) 使用 enumerate 函數(shù)獲取每個元素的索引 i 和值 num,if i % 2 == 0 是一個條件過濾,只有當(dāng) i 是偶數(shù)時,才會被包含在新的列表 filtered_numbers 中。
11.使用 zip 進行條件過濾
我們可以使用 zip 函數(shù)來同時遍歷多個列表,并進行條件過濾,例如只保留兩個列表中對應(yīng)位置相等的元素。
# 原始列表
list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 6, 4, 7]
# 列表推導(dǎo)式加條件過濾
filtered_numbers = [a for a, b in zip(list1, list2) if a == b]
print(filtered_numbers) # 輸出: [1, 2, 4]
解釋:這里,for a, b in zip(list1, list2) 使用 zip 函數(shù)同時遍歷 list1 和 list2,if a == b 是一個條件過濾,只有當(dāng) a 和 b 相等時,才會被包含在新的列表 filtered_numbers 中。
12.使用 filter 函數(shù)進行條件過濾
雖然 filter 函數(shù)不是列表推導(dǎo)式的一部分,但我們可以將其與列表推導(dǎo)式結(jié)合使用,例如只保留平方后大于10的數(shù)字。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 定義過濾函數(shù)
def is_square_greater_than_10(x):
return x ** 2 > 10
# 列表推導(dǎo)式加條件過濾
filtered_numbers = [num for num in filter(is_square_greater_than_10, numbers)]
print(filtered_numbers) # 輸出: [4, 5]
13.使用 any 和 all 進行條件過濾
我們可以使用 any 和 all 函數(shù)來處理更復(fù)雜的條件,例如只保留包含至少一個元音字母的單詞。
# 原始字符串列表
words = ["apple", "banana", "cherry", "date"]
# 列表推導(dǎo)式加條件過濾
vowel_words = [word for word in words if any(vowel in word for vowel in 'aeiou')]
print(vowel_words) # 輸出: ['apple', 'banana', 'cherry', 'date']
解釋:這里,if any(vowel in word for vowel in 'aeiou') 是一個條件過濾,any 函數(shù)檢查 word 中是否包含任何元音字母。如果 word 中包含至少一個元音字母,那么該單詞會被包含在新的列表 vowel_words 中。
14.使用 map 和 filter 結(jié)合列表推導(dǎo)式
我們可以將 map 和 filter 函數(shù)與列表推導(dǎo)式結(jié)合使用,例如將所有數(shù)字轉(zhuǎn)換為字符串,并只保留長度大于3的字符串。
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 列表推導(dǎo)式加條件過濾
filtered_strings = [str(num) for num in map(str, numbers) if len(str(num)) > 3]
print(filtered_strings) # 輸出: []
解釋:這里,map(str, numbers) 將 numbers 中的每個元素轉(zhuǎn)換為字符串。[str(num) for num in map(str, numbers) if len(str(num)) > 3] 是一個列表推導(dǎo)式,它遍歷轉(zhuǎn)換后的字符串列表,并使用 if len(str(num)) > 3 過濾出長度大于3的字符串。在這個例子中,沒有長度大于3的字符串,所以輸出為空列表。
15.使用 set 進行條件過濾
我們可以使用 set 來去重并進行條件過濾,例如只保留唯一的偶數(shù)。
# 原始列表
numbers = [1, 2, 2, 3, 4, 4, 5]
# 列表推導(dǎo)式加條件過濾
unique_even_numbers = [num for num in set(numbers) if num % 2 == 0]
print(unique_even_numbers) # 輸出: [2, 4]
解釋:這里,set(numbers) 將 numbers 轉(zhuǎn)換為一個集合,去除了重復(fù)的元素。[num for num in set(numbers) if num % 2 == 0] 是一個列表推導(dǎo)式,它遍歷去重后的集合,并使用 if num % 2 == 0 過濾出偶數(shù)。
16.使用 dict 進行條件過濾
我們可以使用 dict 來過濾字典中的鍵值對,例如只保留值大于10的鍵值對。
# 原始字典
data = {'a': 5, 'b': 15, 'c': 10, 'd': 20}
# 列表推導(dǎo)式加條件過濾
filtered_items = [(key, value) for key, value in data.items() if value > 10]
print(filtered_items) # 輸出: [('b', 15), ('d', 20)]
解釋:這里,data.items() 返回字典中的鍵值對。[(key, value) for key, value in data.items() if value > 10] 是一個列表推導(dǎo)式,它遍歷字典中的每個鍵值對,并使用 if value > 10 過濾出值大于10的鍵值對。
17.使用 try-except 進行條件過濾
我們可以使用 try-except 塊來處理可能引發(fā)異常的情況,例如只保留可以轉(zhuǎn)換為整數(shù)的字符串。
# 原始字符串列表
strings = ["1", "2", "three", "4", "five"]
# 列表推導(dǎo)式加條件過濾
valid_integers = [int(s) for s in strings if s.isdigit()]
print(valid_integers) # 輸出: [1, 2, 4]
解釋:這里,if s.isdigit() 檢查字符串 s 是否全部由數(shù)字組成。如果是,則使用 int(s) 將其轉(zhuǎn)換為整數(shù)。[int(s) for s in strings if s.isdigit()] 是一個列表推導(dǎo)式,它遍歷 strings 中的每個字符串,并使用 if s.isdigit() 過濾出可以轉(zhuǎn)換為整數(shù)的字符串。
18.使用 sorted 進行條件過濾
我們可以使用 sorted 函數(shù)對列表進行排序,并結(jié)合條件過濾,例如只保留前3個偶數(shù)。
# 原始列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 列表推導(dǎo)式加條件過濾
top_three_evens = sorted([num for num in numbers if num % 2 == 0])[:3]
print(top_three_evens) # 輸出: [2, 4, 6]
解釋:這里,[num for num in numbers if num % 2 == 0] 是一個列表推導(dǎo)式,它遍歷 numbers 中的每個元素,并使用 if num % 2 == 0 過濾出偶數(shù)。sorted(...)[:3] 對過濾后的偶數(shù)進行排序,并取前3個元素。
實戰(zhàn)案例:過濾并統(tǒng)計用戶評分
假設(shè)我們有一個包含用戶評分的列表,我們需要過濾出評分大于等于4的用戶,并統(tǒng)計這些用戶的數(shù)量。
# 原始評分列表
ratings = [3.5, 4.0, 4.5, 3.0, 5.0, 4.2, 3.8, 4.7]
# 列表推導(dǎo)式加條件過濾
high_ratings = [rating for rating in ratings if rating >= 4]
# 統(tǒng)計高評分的數(shù)量
high_rating_count = len(high_ratings)
print(f"高評分的數(shù)量: {high_rating_count}")
print(f"高評分的用戶: {high_ratings}")
解釋:
- ratings 是一個包含用戶評分的列表。
- [rating for rating in ratings if rating >= 4] 是一個列表推導(dǎo)式,它遍歷 ratings 中的每個評分,并使用 if rating >= 4 過濾出評分大于等于4的用戶。
- len(high_ratings) 計算高評分的數(shù)量。
- 最后,輸出高評分的數(shù)量和具體的高評分用戶。