根据其他堆栈中的答案,我来自 MATLAB 背景,到目前为止,这个简单的操作在 Python 中实现似乎非常复杂。通常,大多数答案都使用 for 循环。
到目前为止我见过的最好的是
import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)
有没有更简单的方法?
注意:由于我们已经有vanilla Python、list comprehensions 和 map的副本,并且我还没有找到一个副本来平方一维 numpy array,所以我想我会保留使用的原始答案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])
numpy.power()
还有一个更通用的numpy.power()
>>> np.power(start_list, 2)
array([25, 9, 1, 4, 16])
最易读的可能是列表推导:
start_list = [5, 3, 1, 2, 4]
b = [x**2 for x in start_list]
如果您是功能类型,您会喜欢map
:
b = map(lambda x: x**2, start_list) # wrap with list() in Python3
只需使用列表理解:
start_list = [5, 3, 1, 2, 4]
squares = [x*x for x in start_list]
注意:作为一个小的优化,doingx*x
比x**2
(或pow(x, 2))
.