小编Joa*_*ner的帖子

如何在Python中使用零初始化整数array.array对象

标题相似的问题与Python列表或NumPy有关。这与标准Python库的array.array类有关,请参阅https://docs.python.org/2/library/array.html

我想出的快速方法(对于整数类型)是将array.fromfile与/ dev / zero一起使用。这是

  • 大约比array.array('L',[0] * size)快27倍,后者临时需要的内存是最终数组的两倍多,
  • 比arrar.array('L',[0])* size快4.7倍
  • 比使用自定义可迭代对象快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 …
Run Code Online (Sandbox Code Playgroud)

python arrays initialization

5
推荐指数
1
解决办法
551
查看次数

标签 统计

arrays ×1

initialization ×1

python ×1