列表推導式使用 any()
的 10 個實用範例:
1. 檢查列表中是否有負數
numbers = [1, -2, 3, 4]
has_negative = any(x < 0 for x in numbers) # True
2. 判斷字串列表中是否包含空字串
strings = ["apple", "", "banana", "cherry"]
has_empty = any(s == "" for s in strings) # True
3. 檢查是否有學生成績低於及格線
scores = [80, 60, 55, 90]
has_failed = any(score < 60 for score in scores) # True
4. 確認列表中是否存在奇數
numbers = [2, 4, 6, 7]
has_odd = any(x % 2 != 0 for x in numbers) # True
5. 檢查文件名列表中是否包含目標副檔名
files = ["file1.txt", "file2.doc", "file3.pdf"]
has_txt = any(file.endswith(".txt") for file in files) # True
6. 判斷字典中是否有值為零
data = {"a": 5, "b": 0, "c": 10}
has_zero = any(value == 0 for value in data.values()) # True
7. 檢查字串是否包含任何數字
text = "Hello123"
contains_digit = any(char.isdigit() for char in text) # True
8. 確認矩陣的任何一行是否為空
matrix = [[1, 2], [], [3, 4]]
has_empty_row = any(len(row) == 0 for row in matrix) # True
9. 判斷是否存在大於 100 的數字
numbers = [50, 75, 101, 30]
has_large = any(x > 100 for x in numbers) # True
10. 檢查兩個列表中是否有對應的相等元素
list1 = [1, 2, 3]
list2 = [4, 2, 6]
has_match = any(x == y for x, y in zip(list1, list2)) # True
沒有留言:
張貼留言