首页 > 其他 > 详细

map()函数的用法

时间:2020-04-08 01:35:51      阅读:82      评论:0      收藏:0      [点我收藏+]

map()函数的用法

map()函数作用:对列表里每个元素都用函数计算,返回一个新列表。

map()函数有两类参数:一个函数和若干列表。

这个函数有几个参数,map()后面就有几个列表。

1 - 一个函数处理一个列表

my_list_0 = map(lambda x: x * x, [1, 2, 3, 4, 5, 6])
for i in my_list_0:
    print(i)

运行结果:

1
4
9
16
25
36
特殊用法
my_list_0 = map(int,‘12345‘)
for i in my_list_0:
    print(type(i))
    print(i)

运行结果:

<class ‘int‘>
1
<class ‘int‘>
2
<class ‘int‘>
3
<class ‘int‘>
4
<class ‘int‘>
5

2 - 一个函数处理多个列表

my_list_1 = map(lambda x, y: x ** y, [1, 2, 3], [1, 2, 3])
for i in my_list_1:
    print(i)

运行结果:

1
4
27

3 - 一个函数处理多个列表,列表长度不一致,可以

my_list_3 = map(lambda x, y: (x ** y, x + y), [1, 2, 3], [1, 2])
for i in my_list_3:
    print(i)

运行结果:

(1, 2)
(4, 4)

4 - 一个函数处理多个列表,列表元素类型不一致,不可以

my_list_4 = map(lambda x, y: (x ** y, x + y), [1, 2, 3], [1, 2,‘a‘])
for i in my_list_4:
    print(i)

运行结果:

TypeError: unsupported operand type(s) for ** or pow(): ‘int‘ and ‘str‘
(1, 2)
(4, 4)

5 - 函数为None,列表不限

print(map(None,[1,2,3,4,5,6]))
print(map(None,[2,3,4],[1,2,3]))

运行结果

<map object at 0x006594C0>
<map object at 0x00659AC0>

map()函数的用法

原文:https://www.cnblogs.com/gnuzsx/p/12657087.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!