<分区>
我来自 MATLAB 背景,根据其他堆栈中的答案,到目前为止,这个简单的操作在 Python 中实现似乎非常复杂。通常,大多数答案都使用 for 循环。
到目前为止我看到的最好的是
import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)
有没有更简单的方法?
<分区>
我来自 MATLAB 背景,根据其他堆栈中的答案,到目前为止,这个简单的操作在 Python 中实现似乎非常复杂。通常,大多数答案都使用 for 循环。
到目前为止我看到的最好的是
import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)
有没有更简单的方法?
最佳答案
注意:因为我们已经有了 vanilla Python, list comprehensions and map 的副本而且我还没有找到一个重复项来对 1D numpy 数组 进行平方,我想我会保留使用 numpy
numpy.square()
如果您是从 MATLAB 转到 Python,那么为此尝试使用 numpy 绝对是正确的。使用 numpy 你可以使用 numpy.square()
返回输入的元素平方:
>>> 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])
关于python - 在 Python 中对数字列表(或数组?)进行平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35696811/
相关文章:
python - 在 python 函数中,我是否需要预先分配一个在 if 下有条件出现的值?
python - 尽管有制表符或空格,如何检查字符串是否在行首?
广场连接API : Retrieving all items within a category
java - 在 spring 构造函数中注入(inject)使用构建器模式的对象
python - 使用准备好的数据进行 Sci-kit 分类
python - pymysql 不插入数据;但 "autoincrement"增加
python - python-opencv-headless 的问题
javascript - Square 是否在 SqPaymentForm 中接受 Android Pay?
xcode - React-native/iOS 应用程序 : Module 'SquareInAppPaymentsSDK' not found, 虽然它已添加到项目中