Multiple operations for each number in the python square list

Time:2021-10-18

Multiple operations for each number in the python square list

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]

Supplement: several methods of finding the square root and square of numbers in Python

Method 1: use the built-in module

  1. >>> import math
  2.  
  3. >>>Math. Pow (12, 2) # square
  4. 144.0
  5.  
  6. >>>Math. Sqrt (144) # find the square root
  7. 12.0
  8.  
  9. >>>

Method 2: use expression

  1. >>>12 * * 2 # square
  2. 144
  3.  
  4. >>>144 * * 0.5 # find square root
  5. 12.0
  6.  
  7. >>>

Method 3: use built-in functions

  1. >>>Pow (12, 2) # square
  2. 144
  3.  
  4. >>>Pow (144,. 5) # find the square root
  5. 12.0
  6.  
  7. >>>

The above is personal experience. I hope you can give us a reference and support us. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]