- lambda表达式
g = lambda x, y: x * y
print(g(2, 3))
其中x, y是参数, 这是一个匿名函数,用g来接收
运行结果
6
- filter过滤器
print(filter(None , [1,2,True, False,0,5]))
print(list(filter(None , [1,2,True, False,0,5])))
运行结果
<filter object at 0x000002ED570EE748>
[1, 2, True, 5]
可见filter()返回的是可迭代的对象
同时功能是将为false的值过滤掉
看到这里我们看一下filter的帮助文档
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
可以看到filter的第一个参数可以是一个function
那接下来我来定义一个返回奇数的方法
def odd(x):
return x % 2
print(filter(odd, range(10)))
print(list(filter(odd, range(10))))
运行结果
<filter object at 0x00000299109CE908>
[1, 3, 5, 7, 9]
将上面的用lambda表达式实现
print(filter(lambda x: x % 2, range(10)))
print(list(filter(lambda x: x % 2, range(10))))
运行结果同上
- map()
print(map(lambda x: x * 2, range(10)))
print(list(map(lambda x: x * 2, range(10))))
运行结果
<map object at 0x00000210AE658F08>
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]