Python学习之路(十三)-常用函数的使用,及优化

Python 语言中有一些常用的函数,它们在日常编程中非常实用


1. map() 函数

使用方式

map() 函数将一个函数应用于可迭代对象(如列表、元组等)的所有元素,并返回一个新的可迭代对象。

# 示例:将列表中的每个数字平方
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # 输出:[1, 4, 9, 16]
优化建议
  • 当需要对大量数据进行简单操作时,map() 比显式的 for 循环更简洁。
  • 如果逻辑较复杂,优先使用 for 循环以提高代码可读性。
  • 可以结合 lambda 表达式实现简洁的匿名函数。

2. filter() 函数

使用方式

filter() 函数用于过滤序列,保留满足条件的元素。

# 示例:筛选出偶数
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出:[2, 4]
优化建议
  • map() 类似,适用于简单的过滤逻辑。
  • 对于复杂的判断逻辑,可以定义单独的函数来替代 lambda 表达式。

3. reduce() 函数

使用方式

reduce() 函数需要从 functools 模块导入,它将一个函数累积地应用到可迭代对象的所有元素上,最终得到一个单一的结果。

from functools import reduce

# 示例:计算列表所有元素的乘积
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 输出:24
优化建议
  • 适合用于累加、累乘等场景。
  • 注意处理空列表的情况,避免引发异常。

4. zip() 函数

使用方式

zip() 函数将多个可迭代对象按位置组合成一个元组的列表。

# 示例:将两个列表合并为元组列表
names = ["Alice", "Bob"]
scores = [85, 90]
combined = list(zip(names, scores))
print(combined)  # 输出:[('Alice', 85), ('Bob', 90)]
优化建议
  • 在处理多个并行数据时非常有用。
  • 如果输入的长度不一致,结果会以最短的为准。

5. enumerate() 函数

使用方式

enumerate() 函数用于遍历可迭代对象的同时获取索引和值。

# 示例:打印列表的索引和值
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(index, fruit)
优化建议
  • 替代传统的 for i in range(len(...)) 写法,代码更简洁。
  • 提高可读性,尤其在需要索引的场景中。

6. sorted()list.sort() 函数

使用方式

sorted() 返回排序后的新列表,而 list.sort() 会原地修改原始列表。

# 示例:对列表进行排序
numbers = [3, 1, 4, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出:[1, 2, 3, 4]

# 原地排序
numbers.sort()
print(numbers)  # 输出:[1, 2, 3, 4]
优化建议
  • 使用 key 参数自定义排序规则(例如按字符串长度排序)。
  • 对大型数据集排序时,注意性能开销。

7. itertools 模块

常用函数
  • itertools.product():笛卡尔积。
  • itertools.permutations():排列。
  • itertools.combinations():组合。
import itertools

# 示例:生成两个列表的笛卡尔积
a = [1, 2]
b = ['x', 'y']
print(list(itertools.product(a, b)))  # 输出:[(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y')]
优化建议
  • 避免直接生成超大数据集,尽量使用惰性求值特性。
  • 适合解决组合问题,但需要注意时间复杂度。

8. collections 模块

常用类
  • Counter:统计元素出现次数。
  • defaultdict:带默认值的字典。
  • deque:高效的双端队列。
from collections import Counter

# 示例:统计列表中元素的频率
words = ["apple", "banana", "apple", "orange"]
word_count = Counter(words)
print(word_count)  # 输出:Counter({'apple': 2, 'banana': 1, 'orange': 1})
优化建议
  • 在需要高效统计或数据结构时使用。
  • 熟悉其内部实现原理,避免过度依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香蕉可乐荷包蛋

努力写有用的code

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值