Python basics - anonymous functions and built-in functions

Anonymous functions and built-in functions

Anonymous function: no name, ie, once recovered, can function bracketed run.

  • Syntax : the lambda parameters: return value

  • Use :

    • The anonymous function assigned to a variable, a function name to anonymous, use this variable to call (might as well use a named function)
    res = lambda x,y:x*y
    print(res(2,3))   # 打印结果:6
    • Together with the use of built-in functions, such as: max, min, the sorted, Map, filter, the reduce

Built-in functions are functions python interpreter for us.

  • max returns the maximum value of a given parameter, this parameter can be iterables

    Syntax : max (iterables, key = function object)

  • min returns a minimum value of the given parameter, this parameter can be iterables

    Syntax : min (iterables, key = function object)

# 需求:求出以下工资最高和工资最低的员工
user_dic = {
    '赵铁柱': 3000,
    '张全蛋': 20000,
    '伍六七': 1500,
    '李小花': 8000
}
s_max = max(user_dic, key=lambda x: user_dic[x])
"""
1.max内部会遍历user_dic,将遍历结果一一传给lambda的参数x
2.依据lambda的返回值作为比较条件,得到最大条件下的那个遍历值
3.对外返回最大的遍历值
"""
print(f"工资最高的员工是:{s_max}")

s_min = min(user_dic, key=lambda x: user_dic[x])
print(f"工资最低的员工是:{s_min}")  # 原理跟max 类似
  • sorted receiving a function key (optional) can be achieved iteration ordering custom object

    Syntax : the sorted (iterables, key = function object, reverse = False)

    reverse: the sort direction by default from small to large, Reverse = True descending

# 1、对列表按照绝对值进行排序
li = [-21, -12, 5, 9, 36]
print(sorted(li, key=lambda x: abs(x)))
"""
sorted()函数按照keys进行排序,并按照对应关系返回list相应的元素:
keys使用lambda函数排序结果 => [5, 9,  12,  21, 36]
                            |  |    |    |   |
      最终结果            => [5, 9, -12, -21, 36]
"""

# 2、假设我们用一组tuple表示学生名字和成绩:
L = [('sean', 75), ('egon', 92), ('Jessie', 66), ('tank', 88)]

# 2.1 请用sorted()对上述列表分别按名字排序
print(sorted(L, key = lambda x : x[0]))
"""
1.sorted内部会遍历L,将遍历结果一一传给lambda的参数x
2.依据lambda的返回值依次进行排序,得到排序后的list列表
3.对外返回排序后的列表
"""
# 输出[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]

# 2.2 再按成绩从高到低排序
print(sorted(L, key = lambda x : x[1], reverse=True))
# 输出[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
  • map mappings. Each value will be modified iterator object, then the object is mapped to a map, the map object may be converted to other types of containers present results. Only convert once

    Syntax: the Map (function objects, iterables)

# 1、求列表[1,2,3,4,5,6,7,8,9],返回一个n*n 的列表
# 常规解决方案
list1 = [1,2,3,4,5,6,7,8,9]
li = []
for i in list1:
    i = i ** 2
    li.append(i)
print(li)

# 使用map 的解决方案
map_obj = map(lambda x: x * x, li)
print(map_obj)  # 打印结果为 map对象
print(list(map_obj))  # 将map 对象转换成列表展示
print(tuple(map_obj))  # 打印为空 ???

From the above results can be found in print, map_objconverted twice and was again print is empty. This is a loud noise, and rest assured, this is not the result I eat! ! ! This is because the map is the nature of the object iterable . list(map_obj) Or for num in map_objsuch statement is to call the iterator, performed __ next __(), consumed iteration object. So, re-use map_objafter, you will find that it was empty.

  • reduce the merger. Obtaining two values from each iteration may be performed subject cumulative basis. The effect is:

    reduce (func, [1,2,3]) is equivalent to func (func (1,2), 3)

    Syntax : the reduce (function object, the object can be iterative, the initial value)

    Note :

    • Use reduce function, the packet must be turned from functools import reduce

    • In sum, an initial default value is 0; when evaluated product, the initial value of 1

from functools import reduce
# 求1-100之内的和
res_sum = reduce(lambda x, y: x + y, range(1, 101), 0)
print(res)

# 求1-9的积
res_pro = reduce(lambda x, y: x * y, range(1, 10))
print(res_pro)
  • filter filtration. The return value of the function Trueor Falsethe decision to retain or discard the element. If it is True "filter out", and added to the filter object.

    Syntax : filter (function objects, iterables)

# 求列表['1A','2A','3C','4C','5A']中,返回不包含A的列表
key_list = ['1A','2A','3C','4C','5A']

filter_obj = filter(lambda key:key.endswith('C'),key_list)

print(filter_obj)  # 打印filter 对象 ----> 
print(list(filter_obj))  # 将filter 对象转换成列表展示
print(tuple(filter_obj))  # 打印出空元组,原理同map 对象

From the above code can be found, filter 对象in essence is a iterable

Extended title

1、请利用filter()筛选出200以内的回数。回数是指从左向右读和从右向左读都是一样的数,例如12321,909
2、现有列表 L = ["1","2","3","5","7","8","4","9","6"]
 1) 求列表中所有偶数组成的最大整数
 2) 求列表中所有奇数组成的最小整数

Guess you like

Origin www.linuxidc.com/Linux/2019-11/161397.htm