脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 平方列表中每个数字的多种操作

Python 平方列表中每个数字的多种操作

2021-09-18 00:26Loewi大湿 Python

这篇文章主要介绍了Python 平方列表中每个数字的多种操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

Python 平方列表中每个数字的多种操作

map

map(function,iterable)

  1. x = [1,2,3,4,5]
  2. def square(num):
  3. return num*num
  4. print(list(map(square,x)))
  5. #output:[1, 4, 9, 16, 25]

lambda

lambda x:

  1. x = [1,2,3,4,5]
  2. print(list(map(lambda num:num*num, x)))
  3. #output:[1, 4, 9, 16, 25]

list comprehensions

[funtion for item in iterable]

  1. print([ num*num for num in [1,2,3,4,5]])
  2. #output:[1, 4, 9, 16, 25]

补充:Python中求数字的平方根和平方的几种方法

方法一:使用内置模块

  1. >>> import math
  2.  
  3. >>> math.pow(12, 2) # 求平方
  4. 144.0
  5.  
  6. >>> math.sqrt(144) # 求平方根
  7. 12.0
  8.  
  9. >>>

方法二:使用表达式

  1. >>> 12 ** 2 # 求平方
  2. 144
  3.  
  4. >>> 144 ** 0.5 # 求平方根
  5. 12.0
  6.  
  7. >>>

方法三:使用内置函数

  1. >>> pow(12, 2) # 求平方
  2. 144
  3.  
  4. >>> pow(144, .5) # 求平方根
  5. 12.0
  6.  
  7. >>>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/weixin_42317507/article/details/84190576

延伸 · 阅读

精彩推荐