学习Python中的 filter()函数

829 阅读3分钟

Python filter() Function

Python filter() 函数是另一个[内置]函数,在处理数据时很有帮助。filter() 函数除了接受一个序列作为输入外,实际上还接受一个函数作为输入,并返回一个由给定的序列中的项目构造的迭代器,对于这些项目,给定的函数返回 true。如果你想同时收集结果中的所有内容,你可以对filter产生的迭代器调用[list()]函数。


使用Lambda的filter()

我们最近学习了[Python 中的 lambda 函数],它们与我们在这里讨论的filter()函数一起使用非常普遍。让我们看一个实际的例子,看一个数字列表,只过滤掉偶数的数字。

# Python Program to find even numbers
# from a list using an anonymous function

# Take a list of numbers.
list_of_ints = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# use anonymous lambda function to filter
result = list(filter(lambda x: (x % 2 == 0), list_of_ints))

# printing the result
print(result)
[2, 4, 6, 8]

过滤器和lambda的例子二

接下来的例子是看一个字符串列表。其中一些字符串是回文。这意味着它们的反向拼写与正常情况下是一样的。我们可以使用filter()和lambda函数,只找到列表中的回文。

# Python Program to find palindromes in a list of strings.

list_of_strings = ['ferrari', 'racecar', 'tesla', 'level', 'technoking']

# use an anonymous function to filter palindromes.
result = list(filter(lambda x: (x == ''.join(reversed(x))), list_of_strings))

# print the palindromes
print(result)
['racecar', 'level']

使用filter()的自定义函数

我们也可以使用 Python 中的标准def关键字来定义一个有名字的函数,然后将这个有名字的函数与 filter() 函数结合使用。这里我们将创建一个可以从列表中过滤奇数的函数。

# list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]


# function that finds odd numbers
def is_odd(num):
    if (num % 2) != 0:
        return True
    else:
        return False


results = filter(is_odd, numbers)
print(list(results))
[1, 3, 5, 7, 9, 11]

使用 filter() 删除重复的数字

meats1 = ['steak', 'chicken', 'pork', 'bacon', 'ground beef']
meats2 = ['sausage', 'pork', 'duck', 'lamb', 'steak']


# function that filters duplicate string
def filterDuplicate(string_to_check):
    if string_to_check in the_list:
        return False
    else:
        return True


# Using filter() to remove duplicate strings
the_list = meats2
results = list(filter(filterDuplicate, meats1))
the_list = meats1
results += list(filter(filterDuplicate, meats2))

print("Duplicates removed: ", results)
Duplicates removed:  ['chicken', 'bacon', 'ground beef', 'sausage', 'duck', 'lamb']

filter()检查真值

要理解 filter() 函数的一个关键概念是,它正在检查一个 True 条件。只有真值才能通过过滤器。我们可以通过将Python的None值作为函数传递给filter()来证明这一点,该函数仍将工作。让我们在这里看看这个概念。

# list of values
list_of_values = ['1', 2, 0, False, True, '1', [], {}]

filtered_list = filter(None, list_of_values)

print('The filtered elements are:')
for element in filtered_list:
    print(element)
The filtered elements are:
1
2
True
1

在 Dict 中使用 filter()

到目前为止,我们已经看到了一些如何在各种列表中使用 filter() 的例子。我们还可以在 Python 中对字典使用 filter() 函数。

dictOfNames = {
    0: 'Rick',
    1: 'Vick',
    2: 'Bob',
    3: 'Rob',
    4: 'Soham',
    5: 'Dave'
}

# Filter dictionary by keeping elements whose values contain
# the letter 'a'
newDict = dict(filter(lambda elem: 'a' in elem[1], dictOfNames.items()))
print('Filtered Dictionary : ')
print(newDict)
Filtered Dictionary : 
{4: 'Soham', 5: 'Dave'}

Python filter() 函数总结

filter() 函数从一个迭代器的元素中构造一个迭代器,对于这个迭代器,一个函数返回 true。其工作方式是 filter() 方法在一个函数的帮助下过滤给定的迭代器,该函数测试迭代器中的每个元素是否为真。

filter()函数的语法如下:

filter(function, iterable)

filter()的参数是functioniterable

  • function- 测试迭代器中的元素是否返回真或假的函数
    如果没有,函数默认为Identity函数 - 如果有元素为假,则返回假
  • iterable- 要被过滤的迭代器,可以是集合、列表、图元或任何迭代器的容器。

filter()函数返回一个迭代器,该迭代器通过了迭代器中每个元素的函数检查。

使用lambda时,filter()函数的语法如下:

filter(lambda item: item[] expression, iterable)