Python中的高阶函数和内置高阶函数(abs,map,reduce,sorted,filter)

  • 高阶函数
    1.实参是一个函数名
    2.函数的返回值是一个函数

1.abs:

求绝对值

def fun(a,b):
    return a + b
a = fun(1,2)
print(a)
print(abs(-11))
输出结果:
3
11

(1)函数本身也可以赋值给变量,变量也可以指向函数

f = abs
print(f(-10))
结果:
10

(2)传递的参数包括函数名

def fun(x,y,f):
    return f(x),f(y)
print(fun(-10,23,abs))
结果:
(10, 23)

注:

f = abs 表示把整个函数本身赋值给f
f = abs() 表示把函数的返回值赋值给f

2.map:

map()函数接收两个参数,一个是函数,一个是序列
map将传入的函数依次作用到序列的每个元素,并把结果作为新的序列返回
(1)对于序列[-1,3,-5,-4]的每个元素求绝对值

import random
print(map(abs,[-1,3,-5,-4]))
输出回报错:因为map()打印的不是一个列表而是一个对象,可以将其转化成一个列表再打印
print(list(map(abs,[-1,3,-5,-4])))
结果:
[1, 3, 5, 4]

(2)对于序列的每个元素求阶乘(10个元素,都在2~7之间的随机数)

def factoric(x):
    res = 1
    for i in range(1,x+1):
        res *= i
    return res
li = [random.randint(2,7) for i in range(10)]
print(li)
print(list(map(factoric,li)))
结果:
[5, 4, 4, 7, 3, 6, 2, 5, 6, 6]
[120, 24, 24, 5040, 6, 720, 2, 120, 720, 720]

练习:
用户接收一串数字,‘1 3 5 7 8’,将字符串中所有的数字转化为整型,并且以列表的格式输出

   s = '1 3 5 7 8'
   print(list(map(int,s.split())))
   结果:
   [1, 3, 5, 7, 8]

3.reduce:

reduce:把一个函数作用在一个序列上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
reduce(f,[x1,x2,x3,x4,x5] = f(f(f(x1,x2),x3),x4)

from functools import reduce    ##只导入funtools包里的reduce工具
#累乘
def multi(x,y):
    return x * y
print(reduce(multi,range(1,5)))
#累加
def add(x,y):
    return x + y
print(reduce(add,[1,2,3,4,5]))
结果:
24
15

4.filter过滤函数

和map()类似,也接收一个函数和一个序列
但fileter()把传入的函数依次作用于每个元素,然后根据返回值
是True还是False来决定保留还是丢弃该元素

例:输出1-100中所有的偶数

def isodd(num):
    if num % 2 == 0:
        return True
    else:
        return False
print(list(filter(isodd,range(100))))

5.sorted:排序函数

reverse=True生成倒序

li = [2,1,3,4]
li.sort(reverse=True)     ##用sort()方法
print(li)
a = sorted(li,reverse=True)   ##用sorted函数
print(a)
结果:
[4, 3, 2, 1]

例2:

info = {
    #商品名称 商品数量 商品价格
    ('apple1',200,32),
    ('apple2',40,12),
    ('apple3',40,2),
    ('apple4',1000,23),
    ('apple5',40,5),
}
print(sorted(info))

##按照商品数量进行排序
def sorted_by_count(x):
    return x[1]

#按照商品价格进行排序
def sorted_by_price(x):
    return x[2]

#先按照商品数量由小到大排序,如果商品数量一样
#则按照商品价格由小到大排序
def sorted_by_count_price(x):
    return x[1],x[2]

print(sorted(info,key=sorted_by_count))
print(sorted(info,key=sorted_by_price))
print(sorted(info,key=sorted_by_count_price))
结果:
  [('apple1', 200, 32), ('apple2', 40, 12), ('apple3', 40, 2), ('apple4', 1000, 23), ('apple5', 40, 5)]
  [('apple2', 40, 12), ('apple5', 40, 5), ('apple3', 40, 2), ('apple1', 200, 32), ('apple4', 1000, 23)]
  [('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('apple4', 1000, 23), ('apple1', 200, 32)]
  [('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('apple1', 200, 32), ('apple4', 1000, 23)] 

练习:
(2018-携程-春招题)题目需求:
给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
输入:
第一行是数组长度, 后续每一行是数组的一条记录;
4
0
7
0
2
输出:
调整后数组的内容;
4
7
2
0
0

    len = int(input('len:'))
    li = []
    for i in range(len):
        li.append(int(input()))
    #方法一:
    # for a in li:
    #     if a == 0:
    #         li.remove(a)
    #         li.append(0)
    # for b in range(len):
    #     print(li[b])
    #方法二:
    def remove(i):
        if i == 0:
            return 1
        else:
            return 0
    for n in sorted(li,key=remove):
        print(n)

猜你喜欢

转载自blog.csdn.net/qq_44224894/article/details/88918403