python - 更快的 append 值方法

标签 python optimization numpy append

假设我有一个很大的浮点值列表,我想只选择其中一些查看另一个数组:

result = []
for x,s in zip(xlist, slist):
    if f(s): result.append(x)

在循环开始时,我可以粗略估计有多少条目将通过 f 选择

现在这很慢,我尝试将 list 更改为 array 但只看 append 我变慢了

def f(v):
    for ii in a: v.append(ii)
a = range(int(1E7))
v = []
t = time(); f(v); print time()-t # -> 1.3
v = array.array('i')
t = time(); f(v); print time()-t # -> 3.4

我需要更快,因为这个循环在我的程序中真的很慢。 numpy.array 可以帮助我吗?没有 append 方法。

最佳答案

可能有更好的 numpy 解决方案,但在纯 python 中你可以尝试迭代器:

from itertools import izip

xlist = [1,2,3,4,5,6,7,8]
slist = [0,1,0,1,0,0,0,1]

def f(n):
    return n

results = (x for x,s in izip(xlist, slist) if f(s))

# results is an iterator--you don't have values yet
# and no extra memory is consumed
# you can retrieve results one by one with iteration
# or you can exhaust all values and store in a list

assert list(results)==[2,4,8]

# you can use an array too
# import array
# a = array.array('i', results)

您还可以将此方法与 numpy 数组结合使用,看看它是否更快。查看fromiter constructor .

但是,如果您可以重组代码以使用迭代器,则可以避免生成完整列表,从而完全避免使用 append

不用说,您应该看看是否可以加快 f() 过滤函数的速度,因为它会为每个元素调用一次。

关于python - 更快的 append 值方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10655142/

相关文章:

python - 是否可以将 32 位 ctypes 与 64 位 Python 解释器一起使用?

javascript - 行程优化

optimization - 使用 CUDA 进行蒙特卡洛优化

python - numpy concatenate 不将新数组附加到空多维数组

python - 从 Numpy 3D 数组到 2D 数组的转换

python - 在 python 中使用 sklearn 进行连续数据的逻辑回归

python - Hindmarsh-Rose 模型的相空间轨迹

java - for 循环内的引用类型变量声明

python - 来自 2D pandas 数据框的 Matplotlib 3D 曲面图

python - vscode - 从.py文件所在的当前文件夹读取文件