python实现乘方的几种方式

列表a

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

1.

>>> a=[1,2,3,4,5]
>>> [item*item for item in a]
[1, 4, 9, 16, 25]

2.利用map函数
map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
map() 函数语法:

map(function, iterable, ...)

如:

>>> def square(x):
...   return x ** 2
... 
>>> map(square, a)
[1, 4, 9, 16, 25]

3.用lambda函数替换square函数

>>> map(lambda x,y:x*y, a, a)
[1, 4, 9, 16, 25]

猜你喜欢

转载自blog.csdn.net/wang725/article/details/80382526
今日推荐