python内置函数map()函数用法详解
  TEZNKK3IfmPf 2023年11月13日 40 0

先看map()函数底层封装介绍:

python内置函数map()函数用法详解

 注释中翻译为:

map(func, *iterables)——> map对象

创建一个迭代器,使用来自的参数计算函数每个迭代器。当最短的迭代器耗尽时停止。

作用:

        map(func, lst) ,将传⼊的函数变量 func 作⽤到 lst 变量的每个元素中,并将结果组成新的列表 (Python2)/ 迭代器(Python3) 返回。

注意:

        map()返回的是一个迭代器,直接打印map()的结果是返回的一个对象。

示例代码1:

lst = ['1', '2', '3', '4', '5', '6']
print(lst)
lst_int = map(lambda x: int(x), lst)
# print(list(lst_int))
for i in lst_int:
    print(i, end=' ')
print()
print(list(lst_int))

运行效果:

python内置函数map()函数用法详解

python内置函数map()函数用法详解

 示例代码2:  【传入内置函数】

lst = map(str, [i for i in range(10)])
print(list(lst))
lst_2 = map(str, range(5))
print(list(lst_2))

运行效果:

python内置函数map()函数用法详解

 示例代码3:  【传入自定义函数】

list1 = [1, 2, 3, 4, 5]


def func(x):
    return x ** 2


result = map(func, list1)
print(result)
print(list(result))

运行效果:

python内置函数map()函数用法详解

 示例代码4:  【传入多个可迭代对象】

list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 4, 5, 6]
list3 = [1, 2, 3, 4, 5, 6, 7]


def func1(x, y, z):
    return x + y + z


def func2(x, y, z):
    return x, y, z


result1 = map(func1, list1, list2, list3)
print(result1)
print(list(result1))

result2 = map(func2, list1, list2, list3)
print(result2)
print(list(result2))

运行效果:

python内置函数map()函数用法详解

列表、map和filter组合使用:

示例代码:

lst = [{"name": "dgw1", "age": 26}, {"name": "dgw2", "age": 26}, {"name": "dgw3", "age": 26},
       {"name": "dgw4", "age": 26}, {"name": "dgw5", "age": 26}]

# 列表、map组合使用
ret = list(map(lambda x: x['name'], lst))
print(ret)

# 列表、filter组合使用
ret = list(filter(lambda x: x['name'] != 'dgw1', lst))
print(ret)

# 列表、map、filter组合使用
ret = list(map(lambda x: x['name'], filter(lambda x: x['name'] != 'dgw1', lst)))
print(ret)

运行结果:

python内置函数map()函数用法详解

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   29天前   32   0   0 excelpython
TEZNKK3IfmPf