Python-5高阶函数“map”、“reduce”、“filter”、“sorted”

发布时间 2023-05-08 16:56:33作者: 许个未来—

1.map函数:map(func, iterable)

①功能:处理数据

  把iterable中的数据一个一个拿出来,扔到func中做处理,通过调用迭代器来返回参数。

②参数:func:函数(自定义,或者内置函数)

    iterable:可迭代对象(容器数据,range,迭代器)

③返回值:迭代器(需要迭代出值)

"""
-*- coding: utf-8 -*-
@FileName: 高阶函数.py
@Software: PyCharm
@Time    : 2023/4/28 15:29
@Author  : Panda
"""
from functools import reduce

"""Map函数"""
# 将列表元素变为整数
ls = ['1', '2', '3', '4']
it = map(int, ls)

print(it.__next__())
print(it.__next__())
print(it.__next__())

# 位运算,左移相当于乘,右移相当于除. a << b = a * 2^b  a >> b = a // 2^b(相当于是整除)
print(2 << 3)
print(2 >> 3)
# Output: 16 0
print(5 << 3)
print(5 >> 3)
# Output: 40 0
print(2 << 1)
print(2 >> 1)
# Output: 4 1


# 通过map 将ls对应的值打印出来
ls = ['a', 'b', 'c']
def func(n):
    dic = {10: 'a', 11: 'b', 12: 'c'}
    dic_new = {}
    for k, v in dic.items():
        dic_new[v] = k
    return dic_new[n]


# 将ls里面的所有值挨着传递给func函数里面,此时的函数不要括号
res = map(func, ls)
# 需要强转才可以将res的值显示出来
print(list(res))

 

2.reduce函数:reduce(func, iterable)

①功能:计算数据

  把iterable中的前两个数据拿出来进行计算,将计算出来的值和第三个一起再计算。

②参数:func:函数(自定义,或者内置函数)

    iterable:可迭代对象(容器数据,range,迭代器)

③返回值:计算出的结果

"""Reduce函数"""
# 计算8896
ls = [8, 8, 9, 6]
def func(x, y):
    return x * 10 + y


res = reduce(func, ls)
print(res)
print(reduce(lambda x, y: x * 10 + y, ls))

3.filter函数:filter(func, iterable)

①功能:过滤数据

  在自定义或者内置函数中,将返回True的数据进行保留,返回False的数据进行舍弃。

②参数:func:函数(自定义,或者内置函数)

    iterable:可迭代对象(容器数据,range,迭代器)

③返回值:迭代器

"""filter函数"""
def func2(n):
    if n % 2 == 0:
        return True
    else:
        return False


ls = [12, 15, 16, 58, 96, 77]
it = filter(func2, ls)
print(list(it))
print(list(filter(lambda x: True if x % 2 == 0 else False, ls)))

4.sorted函数:sorted(iterable, key= 函数, reverse=False)

①功能:排序数据

  对数据进行排序

②参数:iterable:可迭代对象(容器数据,range,迭代器)

    key:函数(自定义,或者内置函数)

    reverse:是否倒序,默认从小到大

③返回值:列表

总结:一般使用sorted函数,不要使用sort

  sorted:(1)可以排序所有的容器类型数据

     (2)返回一个新的列表

  sort:    (1)只能排序列表

     (2)基于原来的列表进行排序

"""sorted函数"""
tup = (-100, -30, 99, 2)
res = sorted(tup)
print(res)
# 默认从小到大
print(sorted(tup, key=abs, reverse=True))


def func3(n):
    return n % 10


print(sorted(tup, key=func3))