Python 常用的十个高阶函数

Python   2024-07-11 14:48   188   1  

一、map():批量加工数据

map()函数对序列中的每个元素应用给定的函数,产生新的迭代器。

平方运算

numbers = [1, 2, 3, 4]


squared = map(lambda x: x**2, numbers)
print(list(squared)) # 输出: [1, 4, 9, 16]

二、filter():筛选符合条件的元素

filter()根据提供的函数判断序列中的元素,只保留函数返回值为True的元素。

过滤偶数

numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # 输出: [2, 4]

三、reduce():累积计算

reduce()函数对序列中的元素进行累积操作,需要导入functools模块。

求和

from functools import reduce
numbers = [1, 2, 3, 4]
sum_of_numbers = reduce(lambda x, y: x+y, numbers)
print(sum_of_numbers) # 输出: 10

四、sorted():排序艺术

sorted()不仅可以对序列进行排序,还能接受一个比较函数来自定义排序规则。

按字符串长度排序

words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=len)
print(sorted_words) # 输出: ['date', 'apple', 'cherry', 'banana']

五、any()与all():逻辑判断利器

any()只要序列中有任一元素满足条件即返回True;all()需所有元素均满足条件。

检查列表是否有非零元素

nums = [0, 0, 0, 1]
has_non_zero = any(nums)
print(has_non_zero) # 输出: True

六、enumerate():索引与元素同行

enumerate()同时返回元素及其索引,常用于循环中。

打印索引和元素

fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
 print(f"Index {index}: {fruit}")

七、zip():合并迭代器

zip()可以将多个可迭代对象的元素配对成元组。

合并姓名与年龄

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
people = list(zip(names, ages))
print(people) # 输出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

八、reversed():反向遍历

reversed()返回一个反转的迭代器。

反向打印列表

numbers = [1, 2, 3, 4, 5]
print(list(reversed(numbers))) # 输出: [5, 4, 3, 2, 1]

九、list(), dict(), set():构造容器

这三个函数可将可迭代对象转换为列表、字典或集合。

从元组创建字典

tuples = [(1, 'apple'), (2, 'banana')]
dictionary = dict(tuples)
print(dictionary) # 输出: {1: 'apple', 2: 'banana'}

十、lambda表达式:匿名函数

lambda表达式用于快速定义简单函数,常用于高阶函数的参数。

lambda求和

sum_lambda = lambda x, y: x + y
print(sum_lambda(3, 5)) # 输出: 8

结语

高阶函数,是Python中的一把锋利的宝剑,它们不仅简化了代码,还提高了代码的可读性和可维护性。掌握这些函数,就如同获得了解锁编程难题的魔法钥匙,让代码世界在你手中绽放出无限可能。继续探索,你会发现Python的每一个角落都藏着惊喜。?✨

以上就是本次关于Python高阶函数的分享,希望这些示例能激发你对函数式编程的兴趣,让你的编程之旅更加精彩!

博客评论
匿名用户
说:

11

1
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。
闲言碎语
你所有的忧伤,都来自于你的余额。
赞赏支持

如果觉得博客文章对您有帮助,异或土豪有钱任性,可以通过以下扫码向我捐助。也可以动动手指,帮我分享和传播。您的肯定,是我不懈努力的动力!感谢各位亲~