对列表中的所有元素进行平方

2022-01-19 00:00:00 python return arrays

问题描述

我被告知

编写一个函数 square(a),它接受一个数字数组 a 并返回一个包含平方的每个值的数组.

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

一开始我有

def square(a):
    for i in a: print i**2

但这不起作用,因为我正在打印,并且没有像我被问到的那样返回.所以我尝试了

But this does not work since I'm printing, and not returning like I was asked. So I tried

    def square(a):
        for i in a: return i**2

但这只是我数组的最后一个数字的平方.我怎样才能让它对整个列表进行平方?

But this only squares the last number of my array. How can I get it to square the whole list?


解决方案

你可以使用列表推导:

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

或者你可以map它:

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

或者您可以执行无聊的旧 for-循环,尽管这不像某些 Python 程序员所希望的那样惯用:

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

相关文章