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:\Users\admin\AppData\Local\Programs\Python\Python37\python.exe C:/Users/admin/Desktop/AutoTest/Test/test/test_01/test_01.py
 
[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:\Users\admin\AppData\Local\Programs\Python\Python37\python.exe C:/Users/admin/Desktop/AutoTest/Test/test/test_01/test_01.py
 [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:\Users\admin\AppData\Local\Programs\Python\Python37\python.exe C:/Users/admin/Desktop/AutoTest/Test/test/test_01/test_01.py
 ['Chengzi', 'Jack', 'Wangli']


Process finished with exit code 0

你可能感兴趣的:(Python中map()函数用法)