map()函数用于将指定函数应用于一个或多个可迭代对象的每个元素,返回惰性迭代器。其语法为map(function, iterable, ...),支持单个或多个可迭代对象输入,以最短者为准进行并行映射。相比列表推导式,map()在处理大數據时更省内存,适合复用函数、复杂逻辑及多输入场景。常见应用包括数据类型转换(如str转float)、字符串清洗(如strip)、批量处理对象属性、函数式编程链式操作,以及结合multiprocessing实现并行计算,提升性能。

map()
map()
map(function, iterable, ...)
function
lambda
iterable
map()
function
例如,我们有一个数字列表,想把每个数字都转换成字符串:
numbers = [1, 2, 3, 4, 5]
# 使用map()和str()函数
str_numbers_iterator = map(str, numbers)
print(list(str_numbers_iterator)) # 输出: ['1', '2', '3', '4', '5']
# 或者,如果你需要进行一些计算再转换
def square_and_then_string(x):
return str(x * x)
squared_str_iterator = map(square_and_then_string, numbers)
print(list(squared_str_iterator)) # 输出: ['1', '4', '9', '16', '25']
# 结合lambda表达式,这在很多场景下非常简洁
data = ['apple', 'banana', 'cherry']
upper_data_iterator = map(lambda s: s.upper(), data)
print(list(upper_data_iterator)) # 输出: ['APPLE', 'BANANA', 'CHERRY']需要注意的是,
map()
list()
for
立即学习“Python免费学习笔记(深入)”;
这真的是一个老生常谈,但又非常实际的问题。在我个人的开发经历中,
map()
列表推导式通常写起来更直观、更“Pythonic”,尤其当转换逻辑比较简单时。比如,把一个列表里的每个元素都乘以2:
numbers = [1, 2, 3, 4, 5] # 列表推导式 doubled_numbers_lc = [x * 2 for x in numbers] print(doubled_numbers_lc) # 输出: [2, 4, 6, 8, 10]
用
map()
doubled_numbers_map = map(lambda x: x * 2, numbers) print(list(doubled_numbers_map)) # 输出: [2, 4, 6, 8, 10]
你看,对于这种简单场景,列表推导式确实更简洁,读起来也像一句自然语言。但如果你的转换逻辑已经封装在一个命名函数里,或者这个函数本身就比较复杂,
map()
至于性能,对于小到中等规模的数据集,两者的性能差异微乎其微,甚至列表推导式可能因为直接生成列表而略快。但当处理的数据量非常庞大时,
map()
我的建议是:
map()
map()
map()
map()
map()
看一个例子:
list1 = [1, 2, 3] list2 = [10, 20, 30] # 我们想把两个列表对应位置的元素相加 sum_elements_iterator = map(lambda x, y: x + y, list1, list2) print(list(sum_elements_iterator)) # 输出: [11, 22, 33]
这里,
lambda x, y: x + y
map()
list1
x
list2
y
lambda
一个需要注意的关键点是,如果提供的可迭代对象长度不一致,
map()
map()
list_short = [1, 2] list_long = [10, 20, 30, 40] # 同样是相加 sum_uneven_iterator = map(lambda x, y: x + y, list_short, list_long) print(list(sum_uneven_iterator)) # 输出: [11, 22] # 结果只包含两个元素,因为list_short只有两个元素
这种行为在处理一些需要对齐数据流的场景下非常有用,比如你可能从两个不同的传感器读取数据,但某个传感器的数据流提前结束了,
map()
在实际开发中,
map()
数据清洗与预处理: 这是最常见的用途之一。
str_prices = ['10.5', '20.0', '15.75'] float_prices = list(map(float, str_prices)) print(float_prices) # 输出: [10.5, 20.0, 15.75]
data_points = [10, 20, 30, 40] max_val = max(data_points) normalized_data = list(map(lambda x: x / max_val, data_points)) print(normalized_data) # 输出: [0.25, 0.5, 0.75, 1.0]
lines = [" hello ", "world\n", " python "] cleaned_lines = list(map(str.strip, lines)) print(cleaned_lines) # 输出: ['hello', 'world', 'python']
批量处理对象属性: 当你有一个对象列表,需要对每个对象的某个属性进行统一操作时。
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def get_domain(self):
return self.email.split('@')[-1]
users = [User("Alice", "alice@example.com"), User("Bob", "bob@test.org")]
domains = list(map(lambda user: user.get_domain(), users))
print(domains) # 输出: ['example.com', 'test.org']函数式编程风格:
map()
map()
raw_data = [" 100 ", "200\n", " 300"] # 先去空白,再转整数,再乘以2 processed_data = map(lambda x: int(x) * 2, map(str.strip, raw_data)) print(list(processed_data)) # 输出: [200, 400, 600]
当然,这种链式操作在Python中也可以用列表推导式嵌套实现,但
map
filter
并行处理(结合multiprocessing
map()
multiprocessing
Pool.map()
from multiprocessing import Pool
import os
def expensive_calculation(x):
# 模拟一个耗时的计算
return x * x * x
if __name__ == '__main__': # Windows系统下需要这个保护
numbers = range(1000000)
# 使用默认的CPU核心数
with Pool(processes=os.cpu_count()) as pool:
results = pool.map(expensive_calculation, numbers)
# print(results[:10]) # 打印前10个结果
# print("计算完成")这个例子中,
Pool.map()
expensive_calculation
numbers
map()
总的来说,
map()
以上就是python中map()函数怎么用_Python map()函数用法与实例的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号