假设我有一个很大的浮点值列表,我想只选择其中一些查看另一个数组:
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/