将列表中的所有元素平方 [英] Squaring all elements in a list

查看:45
本文介绍了将列表中的所有元素平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被告知要

编写一个函数 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?

推荐答案

您可以使用列表推导式:

You could use a list comprehension:

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

这篇关于将列表中的所有元素平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆