在 Python 中对数字的列表(或数组?)进行平方

use*_*752 1 python square

根据其他堆栈中的答案,我来自 MATLAB 背景,到目前为止,这个简单的操作在 Python 中实现似乎非常复杂。通常,大多数答案使用 for 循环。

到目前为止我见过的最好的是

import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法?

bak*_*kal 6

注意:由于我们已经有香草 Python、列表推导式和地图的重复项,而且我还没有找到对一维 numpy 数组进行平方的重复项,我想我会保留使用的原始答案numpy

numpy.square()

如果您是从 MATLAB 到 Python,那么尝试为此使用 numpy 绝对是正确的。使用 numpy,您可以使用numpy.square()which 返回输入的元素平方:

>>> import numpy as np
>>> start_list = [5, 3, 1, 2, 4]
>>> np.square(start_list)
array([25,  9,  1,  4, 16])
Run Code Online (Sandbox Code Playgroud)

numpy.power()

还有一个更通用的 numpy.power()

>>> np.power(start_list, 2)
array([25,  9,  1,  4, 16])
Run Code Online (Sandbox Code Playgroud)


L3v*_*han 5

最易读的可能是列表理解:

start_list = [5, 3, 1, 2, 4]
b = [x**2 for x in start_list]
Run Code Online (Sandbox Code Playgroud)

如果您属于功能型,您会喜欢map

b = map(lambda x: x**2, start_list)  # wrap with list() in Python3
Run Code Online (Sandbox Code Playgroud)


Eug*_*ash 5

只需使用列表理解:

start_list = [5, 3, 1, 2, 4]
squares = [x*x for x in start_list]
Run Code Online (Sandbox Code Playgroud)

注意:作为一个小优化,doingx*xx**2(或pow(x, 2)).