来自深入Python 3的迭代器示例
我正在学习Python作为我的第一语言。在CHP7上,有一个如何使用迭代器的示例来自深入Python 3的迭代器示例,python,python-3.x,iterator,Python,Python 3.x,Iterator,我正在学习Python作为我的第一语言。在CHP7上,有一个如何使用迭代器的示例 import re def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, wo
import re
def build_match_and_apply_functions(pattern, search, replace):
def matches_rule(word):
return re.search(pattern, word)
def apply_rule(word):
return re.sub(search, replace, word)
return [matches_rule, apply_rule]
class LazyRules:
rules_filename = 'plural6-rules.txt'
def __init__(self):
self.pattern_file = open(self.rules_filename, encoding='utf-8')
self.cache = []
def __iter__(self):
self.cache_index = 0
return self
def __next__(self):
self.cache_index += 1
if len(self.cache) >= self.cache_index:
return self.cache[self.cache_index - 1]
if self.pattern_file.closed:
raise StopIteration
line = self.pattern_file.readline()
if not line:
self.pattern_file.close()
raise StopIteration
pattern, search, replace = line.split(None, 3)
funcs = build_match_and_apply_functions(
pattern, search, replace)
self.cache.append(funcs)
return funcs
rules = LazyRules()
def plural(noun):
for matches_rule, apply_rule in rules:
if matches_rule(noun):
return apply_rule(noun)
if __name__ == '__main__':
import sys
if sys.argv[1:]:
print(plural(sys.argv[1]))
else:
print(__doc__)
我的问题是:复数(名词)函数中的“for matches\u规则,apply\u rule in rules:”循环如何知道在满足if条件后何时退出?对于该条件,没有StopIteration命令。我希望for循环继续,直到rules.cache完全迭代
谢谢你的帮助 return语句在该点结束函数,向调用者返回一个值。这在几乎任何情况下都可以依赖(如果您有
try..except..else..finally
结构,即使是return
语句也不会阻止执行finally
块)