批处理函数:map、filter、reduce、zip、all、any
map 函数
map(function, iterable, ...) -将函数应用到可迭代对象的每个元素上,返回一个迭代器
详细说明:
- 第一个参数是一个函数
- 第二个起是可迭代对象
- 可以同时处理多个可迭代对象,并行处理
- 会惰性计算,需要使用
list() 等转换为实际数据
| # 基本用法
def square(x):
return x ** 2
numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result)) # [1, 4, 9, 16]
# 使用lambda简化
result = map(lambda x: x**2, numbers)
# 多参数函数处理多个可迭代对象
a = [1, 2, 3]
b = [4, 5, 6]
result = map(lambda x, y: x + y, a, b)
print(list(result)) # [5, 7, 9]
# 类型转换
str_numbers = ['1', '2', '3']
numbers = map(int, str_numbers) # 转换为整数
|
手搓 map 函数(250403实验三)
| def my_map(func, *iters):
return (func(*items) for items in zip(*iters))
|
-
函数参数中的 *iters:
- 表示接收任意数量的可迭代对象并将它们打包成一个元组。
- 例如,调用
my_map(int, ['1', '2'], ['3', '4']) 时,iters 为 (['1', '2'], ['3', '4'])。
-
zip(*iters):
zip() 函数将多个可迭代对象中对应位置的元素打包成元组(按位置组合元素)
- 这里的
*iters 是解包操作,将元组中的每个可迭代对象作为单独参数传给 zip()
- 例如:
iters 为 (['1', '2'], ['3', '4']) 时,zip(*iters) 会生成 ('1', '3'), ('2', '4')
| a, b = my_map(int, input().split())
print(type(a), type(b))
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
print(my_map(lambda x: x**2, a))
print(my_map(lambda x, y: x+y, a, b))
|
filter 函数
filter(function, iterable) - 过滤出可迭代对象中满足条件的元素,返回迭代器
详细说明:
- 第一个参数为筛选函数,返回bool值
- 第二个参数是可迭代对象
- 对每个元素应用函数,保留返回True的元素
| # 过滤偶数
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
result = filter(is_even, numbers)
print(list(result)) # [2, 4, 6]
# 使用lambda简化
result = filter(lambda x: x % 2 == 0, numbers)
# 过滤非空字符串
strings = ['', 'a', ' ', 'hello', '']
result = filter(lambda s: s.strip(), strings)
print(list(result)) # ['a', 'hello']
|
reduce(function, iterable[, initializer]) - 对可迭代对象中的元素进行累积计算。
详细说明:
- 需要从functools模块导入
- 第一个参数是二元运算函数
- 第二个参数是可迭代对象
- 可选
initializer 作为初始值
- 函数依次接收前一次结果和下一个元素
| from functools import reduce
# 计算乘积
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4]
result = reduce(multiply, numbers)
print(result) # 1*2*3*4=24
# 使用lambda简化
result = reduce(lambda x, y: x * y, numbers)
# 带初始值
result = reduce(lambda x, y: x + y, numbers, 100)
print(result) # 100+1+2+3+4=110
# 字符串连接
words = ['Hello', 'World', '!']
result = reduce(lambda x, y: x + ' ' + y, words)
print(result) # "Hello World !"
|
手搓 reduce 函数
| def reduce(func, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
value = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
else:
value = initializer
for element in it:
value = func(value, element)
return value
def multiply(x, y):
return x * y
print(reduce(multiply, [1, 2, 3, 4, 5])) # 输出: 120
|
zip 函数
zip(iterable, iterable, ...) - 将多个可迭代对象组合打包成一个元组迭代器
说明:
- 接收多个可迭代对象作为参数
- 返回一个 zip 对象,这是一个迭代器,每个元素是对应位置的一套元组
- 按位置**并行**迭代全部参数,直到最短的可迭代对象耗尽
- 常与
dict() 结合用于创建字典
| >>> list(zip('abcdefg', range(3), range(4)))
[('a', 0, 0), ('b', 1, 1), ('c', 2, 2)] # range(3)耗尽了
|
应用:
| names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# 组合成(name, age)元组为元素的迭代器
zipped = zip(names, ages)
print(list(zipped)) # [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
# 解压
zipped_data = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
names, ages = zip(*zipped_data)
# 创建字典
person_dict = dict(zip(names, ages))
print(person_dict) # {'Alice': 25, 'Bob': 30, 'Charlie': 35}
# 不等长可迭代对象
nums1 = [1, 2, 3]
nums2 = [4, 5]
print(list(zip(nums1, nums2))) # [(1, 4), (2, 5)] (最短的为准)
|
all 函数
all(iterable) - 检查可迭代对象中是否所有元素都为真
详细说明:
- 对可迭代对象中的每个元素求布尔值
- 如果所有元素都为 True (或可转换为 True),则返回 True
- 空序列返回 True (空真条件)
- 常用于校验多个条件是否全部满足
| # 基本用法
numbers = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in numbers)) # True (全是偶数)
# 空序列
print(all([])) # True
# 表单数据校验
user_input = ['John', '30', 'john@example.com']
print(all(user_input)) # True (所有字段非空)
user_input = ['', '30', 'john@example.com']
print(all(user_input)) # False (有空字段)
|
any 函数
any(iterable) - 检查可迭代对象中是否有任一元素为真
详细说明:
- 对可迭代对象中的每个元素求布尔值
- 如果任一元素为 True (或可转换为 True),则返回 True
- 空序列返回 False
- 常用于检查是否存在满足条件的元素
| # 基本用法
numbers = [1, 3, 5, 8]
print(any(n % 2 == 0 for n in numbers)) # True (存在偶数8)
# 空序列
print(any([])) # False
# 检查错误日志
error_logs = ['INFO', 'WARNING', 'ERROR']
print(any('ERROR' in log for log in error_logs)) # True
ports = [80, 443, 8080]
allowed = any(p in [80, 443] for p in ports)
print(allowed) # True
|