Squaring all elements in a list

后端 未结 10 1127
一整个雨季
一整个雨季 2020-12-01 11:11

I am told to

Write a function, square(a), that takes an array, a, of numbers and returns an array containing each of the values of a squared.

At first, I ha

相关标签:
10条回答
  • 2020-12-01 11:41
    def square(a):
        squares = []
        for i in a:
            squares.append(i**2)
        return squares
    
    0 讨论(0)
  • 2020-12-01 11:42
    def square(a):
        squares = []
        for i in a:
            squares.append(i**2)
        return squares
    

    so how would i do the square of numbers from 1-20 using the above function

    0 讨论(0)
  • 2020-12-01 11:46

    One more map solution:

    def square(a):
        return map(pow, a, [2]*len(a))
    
    0 讨论(0)
  • 2020-12-01 11:51
    from array import *
    
    array('i', [5, 6, 4])
    print(*list(map(pow, vals, [2] * len(vals))), sep='\n')
    
    0 讨论(0)
  • 2020-12-01 11:57

    Use a list comprehension (this is the way to go in pure Python):

    >>> l = [1, 2, 3, 4]
    >>> [i**2 for i in l]
    [1, 4, 9, 16]
    

    Or numpy (a well-established module):

    >>> numpy.array([1, 2, 3, 4])**2
    array([ 1,  4,  9, 16])
    

    In numpy, math operations on arrays are, by default, executed element-wise. That's why you can **2 an entire array there.

    Other possible solutions would be map-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map-based solution that requires lambdas is slower than LC.

    0 讨论(0)
  • 2020-12-01 12:02
    import numpy as np
    a = [2 ,3, 4]
    np.square(a)
    
    0 讨论(0)
提交回复
热议问题