python3怎么调用map函数-Python教程

资源魔 35 0

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']

相干保举:《Python教程》

以上就是python3怎样挪用map函数的具体内容,更多请存眷资源魔其它相干文章!

标签: Python3 python教程 python编程 python使用问题

抱歉,评论功能暂时关闭!