欢迎访问宙启技术站
智能推送

如何使用Python内置函数filter()过滤列表?

发布时间:2023-07-02 11:16:27

Python内置函数filter()用于过滤列表中的元素,其基本用法是通过一个函数和一个可迭代对象来对列表进行过滤操作,返回一个新的经过过滤的列表。

filter()函数的基本语法如下:

filter(function, iterable)

其中,function是一个用来过滤元素的函数,iterable是一个可迭代对象,例如列表、元组、字符串等。

下面是在Python中使用filter()过滤列表的一些常见用法:

1. 过滤偶数:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, lst))
print(even_numbers)  # 输出 [2, 4, 6, 8, 10]

在这个例子中,使用lambda表达式定义了一个匿名函数来过滤偶数。

2. 过滤小写字母:

text = "Hello World"
lowercase_letters = list(filter(lambda x: x.islower(), text))
print(lowercase_letters)  # 输出 ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']

在这个例子中,使用lambda表达式和字符串的islower()方法来过滤小写字母。

3. 过滤长度小于等于3的字符串:

strings = ["apple", "orange", "banana", "pear", "kiwi"]
short_strings = list(filter(lambda x: len(x) <= 3, strings))
print(short_strings)  # 输出 ['pear']

在这个例子中,使用lambda表达式和len()函数来过滤长度小于等于3的字符串。

4. 过滤包含特定字符的字符串:

strings = ["apple", "orange", "banana", "pear", "kiwi"]
filtered_strings = list(filter(lambda x: 'a' in x, strings))
print(filtered_strings)  # 输出 ['apple', 'banana']

在这个例子中,使用lambda表达式和in运算符来过滤包含特定字符的字符串。

5. 过滤大于5的数值:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(lambda x: x > 5, numbers))
print(filtered_numbers)  # 输出 [6, 7, 8, 9, 10]

在这个例子中,使用lambda表达式来过滤大于5的数值。

除了使用lambda表达式,也可以使用自定义的函数作为过滤条件。例如,定义一个函数来过滤负数:

def positive_numbers(x):
    return x > 0

numbers = [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
filtered_numbers = list(filter(positive_numbers, numbers))
print(filtered_numbers)  # 输出 [2, 4, 6, 8, 10]

上述是一些常见的使用filter()函数过滤列表的方法,你可以根据实际需求定制自己的过滤条件和处理逻辑。希望对你有所帮助!