除了循环之外,有没有办法优化这个 python 尝试?

时间:2021-01-02 18:42:48

标签: python optimization try-catch

通常,代码包含一个列表列表 (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_]

2 个答案:

答案 0 :(得分:0)

next 函数接受“默认”参数。您应该能够根据自己的需要使用它。类似的东西:

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

答案 1 :(得分:0)

您可以像这样简化和减少开销:

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() 的默认参数,避免每次循环乘法的开销,并使用基因表达式而不是 filter() 调用。我将它包装在一个函数中,因为本地人比全局人读得更快。让我知道这是否更快。