pythonarray什么意思_python.array与numpy.array

小型引导程序可以使任何人受益,因为它可能有用(遵循@dF的出色回答):

import numpy as np

from array import array

# Fixed size numpy array

def np_fixed(n):

q = np.empty(n)

for i in range(n):

q[i] = i

return q

# Resize with np.resize

def np_class_resize(isize, n):

q = np.empty(isize)

for i in range(n):

if i>=q.shape[0]:

q = np.resize(q, q.shape[0]*2)

q[i] = i

return q

# Resize with the numpy.array method

def np_method_resize(isize, n):

q = np.empty(isize)

for i in range(n):

if i>=q.shape[0]:

q.resize(q.shape[0]*2)

q[i] = i

return q

# Array.array append

def arr(n):

q = array('d')

for i in range(n):

q.append(i)

return q

isize = 1000

n = 10000000

输出结果为:

%timeit -r 10 a = np_fixed(n)

%timeit -r 10 a = np_class_resize(isize, n)

%timeit -r 10 a = np_method_resize(isize, n)

%timeit -r 10 a = arr(n)

1 loop, best of 10: 868 ms per loop

1 loop, best of 10: 2.03 s per loop

1 loop, best of 10: 2.02 s per loop

1 loop, best of 10: 1.89 s per loop

似乎array.array稍微快一点,并且'api'节省了您一些麻烦,但是如果您不仅仅需要存储双精度数,那么numpy.resize毕竟不是一个不好的选择(如果使用正确)。

你可能感兴趣的:(pythonarray什么意思)