我有一個高 CPU 消耗功能,讓我們說:
def high_cost_function(p):
... lots of operations...
return p
我想在 python 的內部回圈下使用:
例子:
paths1= ['a','b','c']
paths2= ['b','c','d']
[any(x.startswith(high_cost_function(y)) for x in paths1) for y in paths2]
哪個回傳正確: [True, True, False]
但是,正如您所看到的,我不得不呼叫high_cost_function(y)路徑 1 中的每個 x。
如果這是一個正常的回圈,我可能會簡單地做:
for y in paths2:
tmp_var = high_cost_function(y)
for x in paths1:
...
use tmp_var
...
無論如何要以第一個“pythonical 時尚方式”來實作它?
uj5u.com熱心網友回復:
迭代已應用的(生成的)ys串列high_cost_function:
[any(x.startswith(y) for x in paths1) for y in map(high_cost_function, paths2)]
uj5u.com熱心網友回復:
deceze的答案對于給定的用例已經很完美了。在更一般的情況下,當您可能還需要y它自己時,您可以使用嵌套生成器運算式(在dict此處創建一個來說明使用兩者):
{y: any(x.startswith(hcf_y) for x in paths1)
for (y, hcf_y) in ((y, high_cost_function(y)) for y in paths2)}
或者使用迭代單元素串列的第二個回圈來在 list-comp 中定義一個變數:
{y: any(x.startswith(hcf_y) for x in paths1)
for y in paths2 for hcf_y in [high_cost_function(y)]}
uj5u.com熱心網友回復:
如果結果high_cost_function不大,還可以使用快取
from functools import lru_cache
@lru_cache(maxsize=None)
def high_cost_function(p):
... lots of operations...
return p
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345157.html
下一篇:如何從字串中洗掉回文單詞
