python3 map函数

来源:互联网 发布:arm linux centos 编辑:程序博客网 时间:2024/05/20 01:33

map()函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']def split_title_and_name(person):    title = person.split()[0]    lastname = person.split()[-1]    return '{} {}'.format(title, lastname)print(list(map(split_title_and_name, people)))

输出:
[‘Dr. Brooks’, ‘Dr. Collins-Thompson’, ‘Dr. Vydiswaran’, ‘Dr. Romero’]

对于list [1, 2, 3, 4, 5, 6, 7, 8, 9]
如果希望把list的每个元素都作平方,就可以用map()函数:
因此,我们只需要传入函数f(x)=x*x,就可以利用map()函数完成这个计算:

def f(x):    return x*xprint map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
原创粉丝点击