除了循环之外,有没有一种方法可以优化这个python try



通常,代码包含一个列表列表(series_(,其中,以列表的初始值为基础,搜索每个满足特定条件的列表的第一个值。

但是,有些列表不包含值​​满足该标准(其中异常起作用并将任意值添加到Compra_列表(。我对优化try/except部分很感兴趣,因为我要处理数百万个数据,运行代码需要几个小时。

for i in range(len(d)):
series_.append(np.array(data2.Close[d[i]:]))

Compra_ = []
for i in series_:
try:
Compra_.append(next(filter(lambda x: x - i[0] >= TH or i[0] - x >= M*TH, i)))
except:
Compra_.append(i[0])

我知道这样的东西会起作用,但是当不满足标准时,它就会停止迭代。

Compra_ = [next(filter(lambda x: x - i[0] >= TH or i[0] - x >= M*TH, i)) for i in series_]

下一个函数接受一个"默认";参数你应该能够根据自己的需要使用它。类似于:

for i in series_:
Compra_.append(next(filter(lambda x: x - i[0] >= TH or i[0] - x >= M*TH, i), i[0]))

使用线程(或多处理(也有助于减少运行时间。类似于:

from concurrent import futures
from concurrent.futures.thread import ThreadPoolExecutor
Compra_ = []
def filter_function(x):
conditions = [
x - i[0] >= TH,
i[0] - x >= M * TH
]
return any(conditions)
with ThreadPoolExecutor as pool:
future_results = {}
for i in series_:
future_results.update(
{pool.submit(next, filter(filter_function, i), i[0]): i}
)
for future in futures.as_completed(future_results):
try:
Compra_.append(future.result())
except Exception as e:
pass # Handle exception

您可以简化并减少开销,如下所示:

def compra():
m_th = M*TH
th = TH
return [
next(
(x for x in xs if x - xs[0] >= th or xs[0] - x >= m_th),
xs[0]
)
for xs in series_
]
Compra_ = compra()

这使用了next()的默认参数,避免了每个循环的乘法开销,并使用了genexpr而不是filter()调用。我把它封装在一个函数中,因为本地读取速度比全局读取速度快。如果速度更快,请告诉我。

相关内容

最新更新