最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python3怎么调用map函数

来源:动视网 责编:小采 时间:2020-11-03 23:19:25
文档

python3怎么调用map函数

python3怎么调用map函数:python3怎么调用map函数?python3中map函数调用语法:map(function, iterable, ...)python源码解释如下:map(func, *iterables) --> map object Make an iterator that computes the function using arg
推荐度:
导读python3怎么调用map函数:python3怎么调用map函数?python3中map函数调用语法:map(function, iterable, ...)python源码解释如下:map(func, *iterables) --> map object Make an iterator that computes the function using arg


python3怎么调用map函数?

python3中map函数调用语法:

map(function, iterable, ...)

python源码解释如下:

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.

简单来说,

map()它接收一个函数 f 和一个 可迭代对象(这里理解成 list),并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

例如,对于list [1, 2, 3, 4, 5, 6, 7, 8, 9]

如果希望把list的每个元素都作平方,就可以用map()函数:

因此,我们只需要传入函数f(x)=x*x,就可以利用map()函数完成这个计算:

def f(x):
 return x*x
print(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

输出结果:

[1, 4, 9, 10, 25, 36, 49, 64, 81]

配合匿名函数使用:

data = list(range(10))
print(list(map(lambda x: x * x, data)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

注意:map()函数不改变原有的 list,而是返回一个新的 list。

利用map()函数,可以把一个 list 转换为另一个 list,只需要传入转换函数。

由于list包含的元素可以是任何类型,因此,map() 不仅仅可以处理只包含数值的 list,事实上它可以处理包含任意类型的 list,只要传入的函数f可以处理这种数据类型。

任务

假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list:

def f(s):
 return s[0:1].upper() + s[1:].lower()
list_ = ['lll', 'lKK', 'wXy']
a = map(f, list_)
print(a)
print(list(a))

运行结果:

<map object at 0x000001AD0A334908>
['Lll', 'Lkk', 'Wxy']

文档

python3怎么调用map函数

python3怎么调用map函数:python3怎么调用map函数?python3中map函数调用语法:map(function, iterable, ...)python源码解释如下:map(func, *iterables) --> map object Make an iterator that computes the function using arg
推荐度:
标签: 使用 如何 map
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top