[英]Fastest way to calculate absolute values of a list
I have a question about calculating the absolute value of a list.我有一个关于计算列表绝对值的问题。 I have written a short code to calculate the absolute value of each single element from a list and I was wondering if there is a faster way of doing this, Thanks!
我写了一个简短的代码来计算列表中每个元素的绝对值,我想知道是否有更快的方法来做到这一点,谢谢!
test_list = [5, -60, 74, -83, -120]
result = [abs(i) for i in test_list]
print(result)
The numpy
package is a package for doing fast maths operations in Python. numpy
包是用于在 Python 中进行快速数学运算的包。 It is so fast because it itself is not actually written in Python (which is a very slow language), but instead in C (which is very fast), and it is very optimised.它之所以如此之快,是因为它本身实际上并不是用 Python(这是一种非常慢的语言)编写的,而是用 C(非常快)编写的,并且非常优化。
After installing numpy:安装 numpy 后:
pip install numpy
This code can be rewritten as:这段代码可以重写为:
import numpy as np
test_list = np.array([5, -60, 74, -83, -120])
result = np.abs(test_list)
print(result)
It will work much faster this way with larger arrays, although bear in mind that for small arrays (like this example), it is not worth it as numpy
takes a while to import.对于较大的数组,它会以这种方式工作得更快,但请记住,对于小型数组(如本例),这是不值得的,因为
numpy
需要一段时间才能导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.