一个函数可以作为另一个函数的变量、参数、返回值等。在数学中,形如y=fn(fn1(x))
def foo():
print("foo")
def bar(func):
func()
print("bar")
bar(foo)
def outer(x): def inner(incr=1): nonlocal x x += 1 return x return inner foo = outer(5)
def outer(x): def inner(incr=1): nonlocal x x += 1 return x return inner foo = outer(5) foo1 = outer(5) print(foo == foo1)
运行结果
False
其功能为:按照函数的的要求过滤可迭代对象iterable中符合条件的元素,返回一个迭代器
接收两个参:
flter(function,iterable)
k = filter(lambda x: x % 2 == 0, [1, 2, 10]) for i in k: print(i)
运行结果
2 10
lst = [1, 2, 10] def filter1(func, iterable): ret = [] for i in iterable: if not func(i): ret.append(i) return ret print(filter1(lambda x: x % 2, lst))
运行结果
[2, 10]
接收两个参数,第一个参数为函数fn,第二个参数为多个可迭代对象iterable,返回一个迭代器
map(function,*iterables) -> map object
print(list(map(lambda x:x+1,range(5))))
运行结果
[1, 2, 3, 4, 5]
def _map(fun, iterable): ret = [] for i in iterable: ret.append(fun(i)) return ret print(_map(lambda x: x + 1, range(5)))
运行结果
[1, 2, 3, 4, 5]
def _map(fun, iterable): ret = {} for i in iterable: ret.setdefault(fun(i), i) return ret print(_map(lambda x: x + 1, range(5))) print(dict(map(lambda x: (x + 1, x), range(5)))) ## 注意,这里的可迭代对象必须是一个二元的
运行结果
{1: 0, 2: 1, 3: 2, 4: 3, 5: 4} {1: 0, 2: 1, 3: 2, 4: 3, 5: 4}
原文:https://www.cnblogs.com/zh-dream/p/13950681.html