Ten, lambda expressions, filter built-in functions of, map, reduce

lambda expressions
 
Learning operation conditions, for simple if else statements, may be used to represent the ternary operator, namely:
# Ordinary conditional statements
if 1 == 1:
name = 'wupeiqi'
else:
name = 'alex'
 
# Ternary operator
name = 'wupeiqi' if 1 == 1 else 'alex'
For simple functions, there is also a simple representation, namely: lambda expression
 
# ###################### ordinary function ######################
#-Defined functions (common mode)
def func1(arg):
return arg + 1
 
# Execute function
func1 (123)
 
# ###################### lambda ######################
 
#-Defined functions (lambda expressions)
func2 = lambda arg : arg + 1
 
# Execute function
func2(123)
 
Lambda is the raison d'etre simple simple function of representation, and also supports pass multiple parameters, and also supports dynamic parameters, as follows:
func3 = lambda a,b: a + b
func3(11,12)
 
 
==============================================================================
==============================================================================
==============================================================================
map method:
Traversal sequence, each element of a sequence operation, eventually acquiring new sequences, such as:
 
Each element 100 increase
= [11,22,33]
def func(arg):
return arg +100
new_list = map(func,li)
print (new_list)
 
Easier to do with a lambda expression:
= [11, 22, 33]
new_list = map(lambda a: a + 100, li)
 
 
两个列表对应元素相加
li = [11, 22, 33]
sl = [1, 2, 3]
new_list = map(lambda a, b: a + b, li, sl)
================================================================================
================================================================================
================================================================================
filter方法:
对于序列中的元素进行筛选,最终获取符合条件的序列,如:
获取列表中大于12的所有元素集合
li = [11, 22, 33]
new_list = filter(lambda arg: arg > 22, li)
#filter第一个参数为空,将获取原来序列,filter内部默认只取值为true的值
以取10以内的所有奇数为例:一行命令搞定
list(filter(lambda x : x % 2,range(10)))
[1,3,5,7,9]
===============================================================================
===============================================================================
===============================================================================
reduce方法:
对于序列内所有元素进行累计操作,如:
获取序列所有元素的和
li = [11, 22, 33,44,55,66,77,88,99]
result = reduce(lambda arg1, arg2: arg1 + arg2, li)
# reduce的第一个参数,函数必须要有两个参数
# reduce的第二个参数,要循环的序列
# reduce的第三个参数,初始值
 

Guess you like

Origin www.cnblogs.com/steven9898/p/11329366.html