lambda函数又称匿名函数,同样有输入和输出,通常作为嵌套函数用,看起来代码更加pythonic。
用法:lambda [parameters]: expression
Python官方手册解释:
An anonymous inline function consisting of a single expression which is evaluated when the function is called.The syntax to create a lambda function is lambda [parameters]: expression
网友总结:
lambda的用法统一是: lambda argument_list: expression
lambda x, y: xy;函数输入是x和y,输出是它们的积xy lambda:None;函数没有输入参数,输出是None
lambda *args: sum(args); 输入是任意个数的参数,输出是它们的和(隐性要求是输入参数必须能够进行加法运算)
lambda **kwargs: 1;输入是任意键值对参数,输出是1
参考:https://blog.youkuaiyun.com/zjuxsl/article/details/79437563
以下为使用示例:
示例1:
>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1])
>>> keys = [r[1] for r in data] # precomputed list of keys
>>> data[bisect_left(keys, 0)]
('black', 0)
>>> data[bisect_left(keys, 1)]
('blue', 1)
>>> data[bisect_left(keys, 5)]
('red', 5)
>>> data[bisect_left(keys, 8)]
('yellow', 8)
示例2:
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
filterfalse(lambda x: x%2,range(10)) --> 0 2 4 6 8
takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
示例3:
lambda x, y: x+y, [1, 2, 3, 4, 5])
con.text_factory = lambda x: x.decode("utf-8") + "foo"
side_effect = lambda value: value + 1
示例4:
for i in range(n_bulk_repeats):
start = time.time()
estimator.predict(X_test)
runtimes[i] = time.time() - start
runtimes = np.array(list(map(lambda x: x / float(n_instances), runtimes)))
map函数用法:
map(function, iterable, …)
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.
Python Lambda 函数详解
本文深入探讨了Python中Lambda函数的定义、语法及应用实例,包括作为排序关键字、过滤条件和映射操作的使用场景,展示了其简洁性和功能性。
566

被折叠的 条评论
为什么被折叠?



