English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 基础教程

Python 流程控制

Fonctions en Python

Types de données en Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Python filter() 使用方法及示例

Python built-in functions

filter()方法从可迭代对象的元素构造一个迭代器,函数将为其返回true。

简单来说,filter()方法在一个函数的帮助下过滤给定的iterable,该函数测试iterable中的每个元素是否为真。

filter()方法的语法为:

filter(function, iterable)

filter()参数

filter()方法采用两个参数:

  • function-

  • 测试iterable的元素返回true还是false的函数,如果为None,则该函数默认为Identity函数-如果任何元素为false,则返回false

  • iterable-要过滤的iterable,可以是集合列表元组或任何迭代器的容器

filter()返回值

filter()方法返回一个迭代器,该迭代器为iterable中的每个元素传递函数检查。

filter()方法等效于:

# 当函数被定义时
(element for element in iterable if function(element))
# 当函数为空时
(element for element in iterable if element)

Example1:filter()如何处理可迭代列表?

# 按字母顺序排列的列表
alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# 过滤元音的函数
def filterVowels(alphabet):
    vowels = ['a', 'e', 'i', 'o', 'u']
    if(alphabet in vowels):
        return True
    else:
        return False
filteredVowels = filter(filterVowels, alphabets)
print('过滤后的元音是:')
for vowel in filteredVowels:
    print(vowel)

When running the program, the output is:

The filtered vowels are:
a
e
i
o

Here, we list a list of letters, and we only need to filter out the vowels from it.

We can use a for loop to traversealphabetsEach element in the list, and store it in another list, but in Python, using the filter() method can make this process easier and faster.

We have a filterVowels function that checks if a letter is a vowel. This function is passed to the filter() method along with the list of letters.

Then, the filter() method passes each letter to the filterVowels() method to check if it returns true. Finally, it creates an iterator that returns true (vowels).

Since the iterator itself does not store values, we traverse it and print out the vowels one by one.

Example2How does the filter() method without a filter function work?

# Random list
randomList = [1, 'a', 0, False, True, '0']
filteredList = filter(None, randomList)
print('The filtered elements are:')
for element in filteredList:
    print(element)

When running the program, the output is:

The filtered elements are:
1
a
True
0

Here,randomListIt is a random list composed of numbers, strings, and boolean values.

We willrandomListThe first parameter passed to filter() (filter function) isNone method.

When the filter function is set to None, the function defaults to the Identity function and checksin randomListWhether each element is true.

When we traverse the finalWhen filtering listThe elements we get are true: (1As 'w', '0', 'True' and '0' are strings, so '0' is also true).

Python built-in functions