1. filter函数
描述
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
函数接收两个参数,第一个为函数,第二个为序列。
filter(function or None, iterable)
序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。如果未设置函数,返回True的值。
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
实例
- 去除序列中的"假值"
>>> listA
[0, 1, 2, False, '', 'FishC', 34]
>>> def remove_false(lst):
return list(filter(None,lst))
>>> remove_false(listA)
[1, 2, 'FishC', 34]
- 过滤出序列中所有的偶数
>>> listB = [i for i in range(10)]
>>>
>>> listB
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def is_even(num):
return num%2 == 0
>>> list(filter(is_even,listB))
[0, 2, 4, 6, 8]
2. map函数
描述
map() 会根据提供的函数对指定序列做映射。
map(function, *iterables)
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回返回迭代器对象,可以使用 list() 来转换。
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
实例
- 计算列表各个元素的平方
>>> listC = [ i for i in range(10) ]
>>> listC
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def sqrt(num):
return num ** 2
>>> list(map(sqrt,listC))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3. lambda表达式
什么是lambda函数
在Python中,我们使用lambda关键字来声明一个匿名函数,这就是为什么我们将它们称为“lambda函数”。匿名函数是指没有声明函数名称的函数。尽管它们在语法上看起来不同,lambda函数的行为方式与使用def关键字声明的一般函数相同。以下是Python中 lambda函数的特点:
- lambda函数可以接受任意数量的参数,但函数只能包含一个表达式。表达式是lambda函数执行的一段代码,它可以返回任何值,也可以不返回任何值。
- lambda函数可以返回函数对象
- 从语法上讲,lambda函数只能有一个表达式。
实例
- 取3个数中最小的数
>>> min_num = lambda x,y,z:x if (x<y and x<z) else (y if y < z else z)
>>> min_num(6,4,5)
4
4. 结合使用
案例
- 结合filter和lambda
#取列表中大于5的数
>>> listD = [ i for i in range(10)]
>>> listD
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(filter(lambda x:x>5, listD))
[6, 7, 8, 9]
- 结合map和lambda
#两个列表的数值相乘,最短的迭代完后停止
>>> listE = [ i for i in range(10)]
>>> listF = [ i for i in range(15)]
>>> list(map(lambda x,y:x*y,listE,listF))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]