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})
优化建议:
- 在需要高效统计或数据结构时使用。
- 熟悉其内部实现原理,避免过度依赖。