在python中是否可以加快列表到数组的转换?
在我的代码中,我注意到将列表转换为数组需要花费大量的时间 我想知道在python中是否有更快的方法将列表转换为数组,下面是我的三个尝试:在python中是否可以加快列表到数组的转换?,python,arrays,python-2.7,list,Python,Arrays,Python 2.7,List,在我的代码中,我注意到将列表转换为数组需要花费大量的时间 我想知道在python中是否有更快的方法将列表转换为数组,下面是我的三个尝试: import numpy as np from timeit import timeit from array import array added_data = range(100000) def test1(): np.asarray(added_data, dtype=np.float16) def test2(): np.ar
import numpy as np
from timeit import timeit
from array import array
added_data = range(100000)
def test1():
np.asarray(added_data, dtype=np.float16)
def test2():
np.array(added_data, dtype=np.float16)
def test3():
array('f', added_data)
print(timeit(test1,number=100))
print(timeit(test2,number=100))
print(timeit(test3,number=100))
换言之:
输入:输出:
from array import array
def test4() :
array = array('d')
for item in added_data: # comma, or other
array.append(item)
但你可以试试:
from array import array
def test5() :
dataset_array = array('d')
dataset_array.extend(added_data)
将项添加到numpy数组将导致性能问题。永远不要那样做 备选方案: 1-将项目添加到列表中,并将该列表转换为numpy数组 2-使用集合中的deque。这是最好的办法
import collections
a = collections.deque([1,2,3,4])
a.append(5)
与您已经尝试过的显而易见的简单方法相比,不太可能有更快的方法将值列表转换为数组。如果有更好的方法,
numpy
作者可能会在np.asarray
或np.array
构造函数本身中实现它。我还想指出的是,array.array
创建的对象远不如numpy
函数复杂,因此它可能不是您想要的
为了提高程序的整体性能,您可以首先避免创建列表。也许您可以使用
np.loadtxt
或np.load
(取决于格式)将外部数据从文件直接读取到数组中。或者,您可以使用np.arange
等函数从头开始生成数组,而不是使用range
等常规Python函数(在Python 2中)返回列表。numpy
模块具有arange(…)
函数。你试过了吗?谢谢你的回答。你的方法会创造,但我在寻找。你是对的。更改为阵列后,情况似乎更糟。感谢您的回复,但它没有回答我的问题。