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

2023-09-02Python开发问题
41

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

问题描述

我被告知

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

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10