0
点赞
收藏
分享

微信扫一扫

Python 函数式编程(三)

小时候是个乖乖 2021-09-29 阅读 66

一. 高阶函数

满足下列条件中任何一个的函数即为高阶函数:

  • 接收一个或多个函数作为参数传入;
  • 返回一个函数。

下面,我们就来介绍几个 Python 中常用的高阶函数。

二. map 函数

map 函数用 func 和可迭代对象中的每一个元素作为参数返回新的可迭代对象。map 函数在使用时需要注意以下几点:

  • func 函数的形参个数必须和提供的可迭代对象的个数相同;
  • 当最短的一个可迭代对象不再提供数据时迭代结束;
  • *ietrable 获取任意多个可迭代对象,封装在一个元组中;
  • map 函数的第一个参数 func,必须有返回值。

示例 1:

>> args = (range(1,4),range(1,4))
>> list(map(lambda x, y : x ** y, *args))
[1, 4, 27]

示例 2:

def mydict(key, value):
    dict_created = {}
    dict_created[key] = value
    return dict_created
 
for dict_item in map(mydict, range(5), "abcde"):
    print(dict_item)

运行结果:

{0: 'a'}
{1: 'b'}
{2: 'c'}
{3: 'd'}
{4: 'e'}

三. filter 函数

filter 函数用于筛选可迭代对象中的数据,返回一个可迭代对象,此可迭代对象对 iterable 提供的数据进行筛选。

参数 function 必须是一个可以返回 bool 值的函数或 lambda 表达式,这样才能对数据起到过滤作用。函数 function 将对 iterable 中的每个元素进行求 bool 值,返回 True 则保留,返回 False 则丢弃。

示例 1:

>> list(filter(lambda x : x % 3 == 0, range(1,10)))
[3, 6, 9]

示例 2:

def is_prime(n):
    """判断n是否为素数"""
    if n < 2:
        return False
    else:
        for number in range(2,n):
            if n % number == 0:
                return False
    return True

运行结果:

>> L = list(filter(is_prime, range(100)))
>> print(L)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

四. sorted 函数

sorted 函数将原可迭代对象提供的数据进行排序,生成排序后的新列表。

使用 sorted 函数时,需要注意以下几点:

  • iterable 是可迭代对象;
  • key 函数是用来提供一个排序参考值的函数,这个函数的返回值将作为排序的依据;
  • reversed 标志用来设置是否降序排序。

示例 1:

>> L = ['Alex', 'Bob', 'Thomas', 'Mathieu', 'Alihanda']
>> sorted(L, key=len, reverse=True)
['Alihanda', 'Mathieu', 'Thomas', 'Alex', 'Bob']

示例 2:

>> L = [{'name':'Alex', 'score':90, 'age':23}, {'name':'Thomas', 'score':80, 'age':27}]
>> update_L = sorted(L, key=lambda x : x['score'], reverse=True)
>> update_L
[{'name': 'Alex', 'score': 90, 'age': 23},
 {'name': 'Thomas', 'score': 80, 'age': 27}]
>> update_L = sorted(L, key=lambda x : x['age'], reverse=True)
>> update_L
[{'name': 'Thomas', 'score': 80, 'age': 27},
 {'name': 'Alex', 'score': 90, 'age': 23}]
举报

相关推荐

0 条评论