gpt4 book ai didi

python - 从生成器函数内部导出重复的代码

转载 作者:太空宇宙 更新时间:2023-11-03 14:03:00 26 4
gpt4 key购买 nike

遵循以下方法:

def _locate(self, text):
"""
This method accesses preceding locators if these exist, it then calls an overridable helper method called _relocate
which receives text with readjusted boundaries and searches inside, the basic implemented behaviour is that of a logical or
"""
if not self.precedents:
for sub_segment in self._relocate(text, Segment(0, len(text), 1)):
if self._multiple:
yield sub_segment
elif self.max_segment.prob > self._prob_threshold:
yield self.max_segment
return
else:
for precedent in self.precedents:
for segment in precedent.locate(text):
for sub_segment in self._relocate(text, segment):
if self._multiple:
yield sub_segment
elif self.max_segment.prob > self._prob_threshold:
yield self.max_segment
return

# if we haven't found a good enough segment return the best one we came across while locating
if not self._multiple:
yield self.max_segment

它有一些重复两次的代码:

for sub_segment in self._relocate(text, segment):
if self._multiple:
yield sub_segment
elif self.max_segment.prob > self._prob_threshold:
yield self.max_segment
return

我天真地认为我可以定义一个辅助方法并只使用一次代码,因此开始实现它,但是,事实证明这几乎是不可能的(因为代码同时使用了产量和返回)并导致了我在代码长度和运行时间方面带来的更多痛苦是值得的。

不确定我到底在问什么(如果有什么问题的话,我可能会问是否有人知道共享生成器代码的通用方法,或者看看如何在这里完成此操作?),但无论如何随着生成器主题的发展,我发现这段经历非常有说服力且有趣,所以我想分享一下。

最佳答案

我认为您可以通过在循环外部定义段生成器来删除代码重复

def _locate(self, text):
"""
This method accesses preceding locators if these exist, it then calls an overridable helper method called _relocate
which receives text with readjusted boundaries and searches inside, the basic implemented behaviour is that of a logical or
"""
if self.precedents:
segments = (seg for precedent in self.precedents for seg in precedent.locate(text))
else:
segments = (Segment(0, len(text), 1),)

for segment in segments:
for sub_segment in self._relocate(text, segment):
if self._multiple:
yield sub_segment
elif self.max_segment.prob > self._prob_threshold:
yield self.max_segment
return

# if we haven't found a good enough segment return the best one we came across while trying
if not self._multiple:
yield self.max_segment

关于python - 从生成器函数内部导出重复的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com