标题相似的问题是关于Python列表或NumPy。这是关于数组.array类是标准Python库的一部分,请参见https://docs.python.org/2/library/array.html
我想出的快速方法(对于整数类型)是使用数组.fromfile使用/dev/zero。这是大约27倍于数组.array('L',[0]*size),它临时需要比最终数组多两倍的内存
大约比数组('L',[0])*尺寸
比使用自定义iterable对象快200多倍(以避免创建一个大的临时列表)。在
但是,在某些平台上,/dev/zero可能不可用。如果没有NumPy、非标准模块或我自己的c扩展,有没有更好的方法来实现这一点?在
演示代码:import array
import sys
import time
size = 100 * 1000**2
test = sys.argv[1]
class ZeroIterable:
def __init__(self, size):
self.size = size
self.next_index = 0
def next(self):
if self.next_index == self.size:
raise StopIteration
self.next_index = self.next_index + 1
return 0
def __iter__(self):
return self
t = time.time()
if test == 'Z':
myarray = array.array('L')
f = open('/dev/zero', 'rb')
myarray.fromfile(f, size)
f.close()
elif test == 'L':
myarray = array.array('L', [0] * size)
elif test == 'S':
myarray = array.array('L', [0]) * size
elif test == 'I':
myarray = array.array('L', ZeroIterable(size))
print time.time() - t