-Lambda function 10. Function

First, the anonymous function analytic

Keyword lambdarepresents an anonymous function, before the colon nrepresents a function parameter can have multiple parameters. Anonymous function has a limit, that is only one expression, do not write return, the return value is the result of the expression.

Anonymous function has the advantage, because the function has no name, do not worry about the function name conflict. In addition, an anonymous function is a function object, you can put anonymous function assigned to a variable, and then use a variable to call the function.

# 这段代码
def calc(x,y):
    return x**y

# 换成匿名函数
calc = lambda x,y:x**y
print(calc(2,5))

def calc(x,y):
    if x > y:
        return x*y
    else:
        return x / y
    
# 三元运算换成匿名函数
calc = lambda x,y:x * y if x > y else x / y
print(calc(2,5))

Second, higher-order functions

1. map()

map () function accepts two arguments, a function, a is Iterable, map the incoming function sequentially applied to each element of the sequence, and the result returned as the new Iterator. Traversal sequence, each element of a sequence operation function, eventually acquiring new sequence.

def func(x):
    return x*x
 
r = map(func, [1, 2, 3, 4, 5])
print(type(r))
r = list(r)
print(r)

输出结果:
<class 'map'>
[1, 4, 9, 16, 
# 1.求列表[1,2,3,4,5,6,7,8,9],返回一个n*n 的列表

#一般解决方案
li = [1,2,3,4,5,6,7,8,9]
for ind,val in enumerate(li):
    li[ind] = val * val
print(li)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]

# 高级解决方案
li = [1,2,3,4,5,6,7,8,9]
print(list(map(lambda x:x*x,li)))
# [1, 4, 9, 16, 25, 36, 49, 64, 81]

2. reduce()

reduce to a function on a sequence [x1, x2, x3, ...], the function must receive two parameters, and continue to reduce the result of the next element in the sequence do cumulative basis, the effect is: reduce ( func, [1,2,3]) is equivalent to func (func (1,2), 3) for all the elements in the cumulative operation sequences.

#接受一个list并利用reduce()求积
from functools import reduce
li = [1,2,3,4,5,6,7,8,9]
print(reduce(lambda x,y:x * y,li))
# 结果=1*2*3*4*5*6*7*8*9 = 362880

3. filter()

filter () also receives a function and a sequence. And map () is different, filter () function is passed the sequentially applied to each element, and based on the return value is True or False decided to keep or discard the element. For the elements of a sequence screening, and ultimately acquire a qualifying sequence

# 在一个list中,删掉偶数,只保留奇数
li = [1, 2, 4, 5, 6, 9, 10, 15]
print(list(filter(lambda x:x % 2==1,li)))  # [1, 5, 9, 15]

# 回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数
li = list(range(1, 200))
print(list(filter(lambda x:int(str(x))==int(str(x)[::-1]),li)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]

4. sorted()

sorted(iterable, /, *, key=None, reverse=False)
  • Receiving a keyfunction to achieve the object may be customized iteration ordering

  • Iterables: mainly lists, strings, tuples, sets, and dictionaries

  • key: receiving a function, according to the result returned by the function, sorting

  • reverse: the sort direction, the default is small to large, reverse = True to reverse

# 对列表按照绝对值进行排序
li= [-21, -12, 5, 9, 36]
print(sorted(li, key = lambda x:abs(x)))
# [5, 9, -12, -21, 36]

"""
sorted()函数按照keys进行排序,并按照对应关系返回list相应的元素:
keys排序结果 => [5, 9,  12,  21, 36]
                |  |    |    |   |
最终结果     => [5, 9, -12, -21, 36]
"""
# 把下面单词以首字母排序
li = ['bad', 'about', 'Zoo', 'Credit']
print(sorted(li, key = lambda x : x[0]))
# 输出['Credit', 'Zoo', 'about', 'bad']
"""
对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。
"""

# 假设我们用一组tuple表示学生名字和成绩:

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# 请用sorted()对上述列表分别按名字排序
print(sorted(L, key = lambda x : x[0]))
# 输出[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]

# 再按成绩从高到低排序
print(sorted(L, key = lambda x : x[1], reverse=True))
# 输出[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]

Guess you like

Origin www.cnblogs.com/hq82/p/11708466.html