使用生成器的好处是显而易见的,可以使代码更加清晰,同时减小内存的消耗,当函数需要返回列表,把函数改写为生成器是相对容易的。
下面这两个函数返回字符串中每个单词的索引:
1 def index_words1(text): 2 result = [] 3 if text: 4 result.append(0) 5 for index, letter in enumerate(text): 6 if letter == ‘ ‘: 7 result.append(index+1) 8 return result 9 10 11 def index_words2(text): 12 if text: 13 yield 0 14 for index, letter in enumerate(text): 15 if letter == ‘ ‘: 16 yield index+1 17 18 19 if __name__ == ‘__main__‘: 20 hhh = ‘Every dog has its day!‘ 21 result = index_words1(hhh) 22 print(‘result1‘, result) 23 result = list(index_words2(hhh)) 24 print(‘result2:‘, result)
参考资料:Effective Python
时间: 2024-10-17 21:34:02