Squaring all elements in a list

后端 未结 10 1128
一整个雨季
一整个雨季 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 12:05

    Use numpy.

    import numpy as np
    b = list(np.array(a)**2)
    
    0 讨论(0)
  • 2020-12-01 12:07

    You could use a list comprehension:

    def square(list):
        return [i ** 2 for i in list]
    

    Or you could map it:

    def square(list):
        return map(lambda x: x ** 2, list)
    

    Or you could use a generator. It won't return a list, but you can still iterate through it, and since you don't have to allocate an entire new list, it is possibly more space-efficient than the other options:

    def square(list):
        for i in list:
            yield i ** 2
    

    Or you can do the boring old for-loop, though this is not as idiomatic as some Python programmers would prefer:

    def square(list):
        ret = []
        for i in list:
            ret.append(i ** 2)
        return ret
    
    0 讨论(0)
  • 2020-12-01 12:08

    you can do

    square_list =[i**2 for i in start_list]
    

    which returns

    [25, 9, 1, 4, 16]  
    

    or, if the list already has values

    square_list.extend([i**2 for i in start_list])  
    

    which results in a list that looks like:

    [25, 9, 1, 4, 16]  
    

    Note: you don't want to do

    square_list.append([i**2 for i in start_list])
    

    as it literally adds a list to the original list, such as:

    [_original_, _list_, _data_, [25, 9, 1, 4, 16]]
    
    0 讨论(0)
  • 2020-12-01 12:08
    numbers = []
    for i in range(10):numbers.append(i)
    result = map(lambda x: x * x * x,numbers)
    print(list(result))
    
    0 讨论(0)
提交回复
热议问题