将 Python 中的数字列表(或数组?)平方
Square a list (or array?) of numbers in Python
我有 MATLAB 背景,根据其他堆栈中的答案,到目前为止,这个简单的操作在 Python 中实现起来似乎非常复杂。通常,大多数答案都使用 for 循环。
到目前为止我看到的最好的是
import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)
有没有更简单的方法?
最可读的可能是列表理解:
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]
注意:作为次要优化,执行 x*x
比 x**2
(或 pow(x, 2))
.
快
您可以使用列表理解:
[i**2 for i in start_list]
或者,如果您使用 numpy
,您可以使用 tolist
方法:
In [180]: (np.array(start_list)**2).tolist()
Out[180]: [25, 9, 1, 4, 16]
或np.power
:
In [181]: np.power(start_list, 2)
Out[181]: array([25, 9, 1, 4, 16], dtype=int32)
注意:因为我们已经有了 vanilla Python, list comprehensions and map 的副本,而且我还没有找到一个副本来平方 1D numpy 数组,我想我会保留使用 numpy
的原始答案
numpy.square()
如果您是从 MATLAB 转到 Python,尝试使用 numpy 绝对是正确的。使用 numpy,您可以使用 numpy.square()
其中 returns 输入的元素平方:
>>> 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])
我有 MATLAB 背景,根据其他堆栈中的答案,到目前为止,这个简单的操作在 Python 中实现起来似乎非常复杂。通常,大多数答案都使用 for 循环。
到目前为止我看到的最好的是
import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)
有没有更简单的方法?
最可读的可能是列表理解:
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]
注意:作为次要优化,执行 x*x
比 x**2
(或 pow(x, 2))
.
您可以使用列表理解:
[i**2 for i in start_list]
或者,如果您使用 numpy
,您可以使用 tolist
方法:
In [180]: (np.array(start_list)**2).tolist()
Out[180]: [25, 9, 1, 4, 16]
或np.power
:
In [181]: np.power(start_list, 2)
Out[181]: array([25, 9, 1, 4, 16], dtype=int32)
注意:因为我们已经有了 vanilla Python, list comprehensions and map 的副本,而且我还没有找到一个副本来平方 1D numpy 数组,我想我会保留使用 numpy
numpy.square()
如果您是从 MATLAB 转到 Python,尝试使用 numpy 绝对是正确的。使用 numpy,您可以使用 numpy.square()
其中 returns 输入的元素平方:
>>> 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])