Python中的Lambda和过滤器示例

在本教程中,我们将看到Python中lambdafilter函数的另一个示例。让我们通过分别了解lambdafilter表达式以及函数来开始本教程。

lambda表达式

lambda表达式用于简单地编写简单函数。假设如果我们想查找偶数,那么编写lambda表达式将为我们节省时间。

如果你不熟悉的拉姆达表达式去的教程部分nhooo了解它的更多细节。

filter(func,iter)函数

filter(func,iter)有两个参数,一个是函数,另一个是iter变量,它返回可以转换为迭代器的filter对象。生成的迭代器将包含通过执行在函数内部编写的某些操作而由func返回的所有元素。

如果你不熟悉的过滤功能去的教程部分nhooo了解它的更多细节。

因此,我们注意到可以在filter(func,iter)函数内部使用lambda表达式。让我们看一个示例,该示例从列表中过滤出偶数。

查看预期的输入和输出。

Input:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output:
[2, 4, 6, 8, 10]

让我们按照以下步骤实现所需的输出。

算法

1. Initialise the list of numbers.
2. Write a lambda expression which returns even numbers and pass it to filter function along with the iter.
3. Convert the filter object into an iter.
4. Print the result.

让我们看一下代码。

示例

## initializing the list
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## writing lambda expression inside the filter function
## every element will be passed to lambda expression and it will return true if it
satisfies the condition which we have written
## filter function function will yield all those returned values and it stores them
in filter object
## when we convert filter object to iter then, it will values which are true
result = filter(lambda x: x % 2 == 0, nums)
## converting and printing the result
print(list(result))

输出结果

如果运行上述程序,将得到以下输出。

[2, 4, 6, 8, 10]

结论