我有一个高 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]
但是,如您所见,我不得不为路径 1 中的每个 x 调用 high_cost_function(y)
。
如果这是一个正常的循环,我可能会简单地做:
for y in paths2:
tmp_var = high_cost_function(y)
for x in paths1:
...
use tmp_var
...
有没有办法以第一种“Python 风格的方式”来实现这个??
最佳答案
遍历已应用 high_cost_function
的(生成的)y
列表:
[any(x.startswith(y) for x in paths1) for y in map(high_cost_function, paths2)]
关于python - 如何避免在内部 Python 样式循环中调用相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69807536/