int*_*ser 3 python arrays copy
除了创建一个新值并复制值或使用and之外,还有一种方法可以在 Python 中复制 an array.array(而不是 a )吗?我似乎在文档中找不到任何内容。如果没有,是否有类似的内置数据类型可以做到这一点?list.to_something.from_something
我正在开发一个高性能模块,所以答案越快越好。
我当前的解决方案只是使用.to_bytesand .from_bytes,根据我的测试,速度大约快 1.8 倍。
不确定你array.array包含什么,但使用示例:
>>> import array\n>>> a = array.array('i', [1, 2, 3] * 1000)\narray('i', [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1,\n2, 3, 1, 2, 3, 1, 2, 3, 1, 2, ... ])\nRun Code Online (Sandbox Code Playgroud)\n\n>>> from copy import deepcopy\n>>> import numpy as np\nRun Code Online (Sandbox Code Playgroud)\n\n切片
\n\nIn [1]: %timeit cp = a[:]\n\n418 ns \xc2\xb1 4.89 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\n深复制
\n\nIn [2]: %timeit cp = deepcopy(a)\n\n1.83 \xc2\xb5s \xc2\xb1 34 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\nnumpy copy ... 注意:这会生成一个 numpy 数组,而不是 array.array
\n\nIn [3]: %timeit cp = np.copy(a)\n\n1.87 \xc2\xb5s \xc2\xb1 62.4 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\n列表理解和 array.array 转换
\n\nIn [4]: %timeit cp = array.array('i', [item for item in a])\n\n147 \xc2\xb5s \xc2\xb1 5.39 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\nnumpy 复制和 array.array 转换
\n\nIn [5]: %timeit cp = array.array('i', np.copy(a))\n\n310 \xc2\xb5s \xc2\xb1 2.25 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\n复制到现有阵列
\n\nIn[6]: pre = array.array('i', [0, 0, 0] * 1000)\nIn[7]: %timeit for i, element in enumerate(a): pre[i] = a[i]\n\n344 \xc2\xb5s \xc2\xb1 7.83 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2965 次 |
| 最近记录: |