Python学习之Part09.高阶函数filter(),map(),reduce(),sorted()

1.高阶函数

  • 一个函数作为参数传给另外一个函数;
  • 一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归)
# abs()用来求一个数的绝对值
# 将abs函数赋值,则f==abs
f = abs
print(f(-10))

# 函数的返回值为另一个函数
def my_abs(x,y):
    return f(x),f(y)

print(my_abs(-10,20))

输出结果:

10
(10, 20)

2.python中的内置高阶函数之map()

map()函数的特性:
    map(fun_name, seq) --> 将函数fun作用在seq中的每个每个值上 最后返回一个列表对象;
    且函数fun必须是接受一个参数,返回一个参数,而不是多个。
# 对一个序列[-1,3,-4,-5]的每一个元素求绝对值
print(map(abs, [-1,-2,-3,7,8,-9]))
print(list(map(abs, [-1,-2,-3,7,8,-9])))
输出结果:
# map()返回一个对象
<map object at 0x7efd2dd320f0>

# list(map())将此对象转换为一个列表
[1, 2, 3, 7, 8, 9]
# 对序列的每个元素求阶乘
import random

# 用来求一个数阶乘的函数
def fun_jiecheng(num):
    res = 1
    for i in range(1, num+1):
        res *= i
    return res

# 随机生成5和1~10的数字
li = [random.randint(1,10) for i in range(5)]
# 使用map()函数将li中的每个元素求阶乘,并将结果作为列表输出
print(list(map(fun_jiecheng, li)))

输出结果: [2, 120, 720, 720, 2]

3.python中的内置高阶函数之reduce()

reduce()函数特性:
    reduce(fun_name, seq) --> reduce返回一个值
    将函数fun作用在一个序列上,fun接受序列的2的元素作为参数,返回一个值
    将此值与序列的下一个元素继续作用
        例如: reduce(fun, [1,2,3,4]) --> fun(fun(fun(1,2),3),4)
    在python 2中,reduce是内置函数
    在python 3中,需要from functools import reduce
# 将一个字符串转换成整型('12345' --> 12345)
from functools import reduce

s = input('Please input number:')
lis = list(map(int, s))

def cov_to_int(x, y):
    return x * 10 + y
print('int type is:', reduce(cov_to_int,lis),' ',type(reduce(cov_to_int,lis)))

输出结果:

Please input number:12345678
int type is: 12345678   <class 'int'>

4.python中的内置高阶函数之filter()

filter()函数特性:
    和map()类似的,filter(fun_name, seq)也接收一个函数和一个列表对象;
    但是函数fun()返回值为True或False;
    filter()把传入的函数依次作用于序列的每个元素,然后根据返回值是True或者False决定保留还是丢弃该元素。
# 过滤10以内的所有偶数
def iseven(num):
    if num%2 == 0:
        return True
    else:
        return False
print(filter(iseven,range(1,10)))
print(list(filter(iseven,range(1,10))))

输出结果:

<filter object at 0x7fb72d451160>
[2, 4, 6, 8]

5.python中的内置高阶函数之匿名函数lambda

lambda:
 冒号之前是传递的参数(可以有多个参数),冒号之后是表达式,返回表达式的值:
 0为假,非0为真

# 输出0~10的累加结果
from functools import reduce
nums = [i for i in range(10)]
print(reduce(lambda x,y:x+y, nums))

输出结果: 45

# 输出10以内的所有偶数
nums = [i for i in range(1, 10)]
print(list(filter(lambda x:x%2==0, nums)))

输出结果: [2, 4, 6, 8]

# 将输入的英文变为首字母大写,其他小写的形式
def my_cov(li):
    return list(map(lambda s:s.title(), li))
li = ['redhat','PYTHON','hEllo']
print(my_cov(li))

输出结果: ['Redhat', 'Python', 'Hello']

# 字符串转换成float型('12345.123' --> 12345.123)
from functools import reduce

s1 = input('Please input number:')
s = s1.split('.')
lis_1 = list(map(int, s[0]))
lis_2 = list(map(int, s[1][::-1]))

def cov_to_int_1(x, y):
    return x * 10 + y
def cov_to_int_2(x,y):
    if 0< x < 1:
        return x*0.1 + y*0.1
    else:
        return x * 0.01 + y * 0.1

res = reduce(cov_to_int_1,lis_1)+reduce(cov_to_int_2,lis_2)
print('float type is:',res,' ',type(res))

输出结果:

Please input number:123789.987321
float type is: 123789.987321   <class 'float'>

6.python中的内置高阶函数之排序函数sorted()

sorted()函数特性:
    sorted()排序,将排序结果存储为一个新的列表来返回;
    默认按照ASC码值的大小进行排序;
    key参数为一个函数,会将需要排序的数据先传参进函数中执行完成后,再将返回值排序
# 将列表排序
s=['bbc','aAc','Aasd','DUF']
print(sorted(s, key=str.lower))

输出结果为: ['aAc', 'Aasd', 'bbc', 'DUF']

# 有一个整数列表(10个元素),按照奇数在前偶数在后进行排序
import random

def fun_trans(num):
    if num%2 == 0:
        return 2
    else:
        return 1

li = [random.randint(1,10) for i in range(10)]
print(sorted(li, key=fun_trans))

输出结果: [7, 7, 1, 8, 8, 10, 2, 4, 4, 2]

# key的使用
info = [
    # 商品名称 商品数量 商品价格
    ('apple1', 200, 100),
    ('apple2', 40, 32),
    ('apple3', 20, 10),
    ('apple4', 20, 15),
]
# 按照商品价格进行排序
print(sorted(info, key=lambda info:info[2]))

输出结果: [('apple3', 20, 10), ('apple4', 20, 15), ('apple2', 40, 32), ('apple1', 200, 100)]

# 按照商品的数量排序:
print(sorted(info, key=lambda info:info[1]))

输出结果:[('apple3', 20, 10), ('apple4', 20, 15), ('apple2', 40, 32), ('apple1', 200, 100)]

# 先按照商品数量进行排序 如果商品数量一致,则按照商品价格进行排序
def fun_num_count(d):
    return d[1],d[2]
print(sorted(info, key=fun_num_count))

输出结果:[('apple3', 20, 10), ('apple4', 20, 15), ('apple2', 40, 32), ('apple1', 200, 100)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值