Python中map()函数用法

时间:2022-07-22
本文章向大家介绍Python中map()函数用法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

map() 是python的内置函数,会根据提供的函数对指定序列做映射。

对可迭代函数*iterables中的每个元素应用func方法,将结果作为迭代器对象返回。

注意:map()函数返回的是一个新的迭代器对象,不会改变原有对象

map()用法
class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
案例一
# 计算平方数
def square(x):
   return x * x
obj = map(square, [1, 2, 3])
print(type(obj), obj)
print(list(obj))

C:UsersadminAppDataLocalProgramsPythonPython37python.exe C:/Users/admin/Desktop/AutoTest/Test/test/test_01/test_01.py
<class 'map'> <map object at 0x0000023BC9B59D88>
[1, 4, 9]

Process finished with exit code 0
案例二
# 使用 lambda 匿名函数计算平方数
square = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
print(square, list(square))

C:UsersadminAppDataLocalProgramsPythonPython37python.exe C:/Users/admin/Desktop/AutoTest/Test/test/test_01/test_01.py
<map object at 0x0000015705389D88> [1, 4, 9, 16, 25]

Process finished with exit code 0
案例三
# 按首字母大写,后字母小写规则显示名字
name_list = ['chengzi', 'JACK', 'wangLi']
def format_name(name_list):
        return name_list[0:1].upper()+name_list[1:].lower()
obj = map(format_name, name_list)
print(obj, list(obj))

C:UsersadminAppDataLocalProgramsPythonPython37python.exe C:/Users/admin/Desktop/AutoTest/Test/test/test_01/test_01.py
<map object at 0x000001FCF0D76708> ['Chengzi', 'Jack', 'Wangli']

Process finished with exit code 0