前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python中map()函数用法

Python中map()函数用法

作者头像
王大力测试进阶之路
发布2020-07-23 11:30:52
4.3K0
发布2020-07-23 11:30:52
举报
文章被收录于专栏:橙子探索测试橙子探索测试

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

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

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

代码语言:javascript
复制
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.
代码语言:javascript
复制
案例一
# 计算平方数
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
<class 'map'> <map object at 0x0000023BC9B59D88>
[1, 4, 9]

Process finished with exit code 0
代码语言:javascript
复制
案例二
# 使用 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
<map object at 0x0000015705389D88> [1, 4, 9, 16, 25]

Process finished with exit code 0
代码语言:javascript
复制
案例三
# 按首字母大写,后字母小写规则显示名字
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
<map object at 0x000001FCF0D76708> ['Chengzi', 'Jack', 'Wangli']

Process finished with exit code 0
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 橙子探索测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档