本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
filter(function, iterable)
-
function:一个用于测试每个元素的函数。该函数对每个元素应用,并返回布尔值 True 或 False; -
iterable:一个可迭代对象,例如列表、元组等。
返回值:
下面是一些使用 filter() 函数的示例:
-
示例 1:
例如使用一个字符串方法,筛选只包含字母的字符串:
# 使用 filter() 过滤出字符串中所有的字母
words = ["hello", "world", "a123", "abc", "456"]
only_letters = filter(str.isalpha, words)
# 将迭代器转换为列表以查看结果
print(list(only_letters))
# 输出:['hello', 'world', 'abc']
-
示例 2:
可以使用自定义函数完成筛选:
# 定义一个函数,返回元素是否为偶数
def is_even(num):
return num % 2 == 0
# 使用 filter() 过滤出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)
# 将迭代器转换为列表以查看结果
print(list(even_numbers))
# 输出:[2, 4, 6, 8, 10]
-
示例 3:
也可以使用 lambda 表达式来简化 filter() 的使用:
# 使用 filter() 和 lambda 过滤出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda num: num % 2 == 0, numbers)
# 将迭代器转换为列表以查看结果
print(list(even_numbers))
# 输出:[2, 4, 6, 8, 10]
-
示例 4:
如果 function 为 None,则 filter() 会返回所有使 iterable 中的元素等价于 True 的元素(即非零、非空、非 False 的元素)。
# 使用 filter() 和 None 过滤出列表中的非零元素
numbers = [0, 1, True, 3, 0, 4, False]
non_zero_numbers = filter(None, numbers)
# 将迭代器转换为列表以查看结果
print(list(non_zero_numbers))
# 输出:[1, True, 3, 4]


本篇文章来源于微信公众号: 码农设计师