首页 > 编程语言 > 详细

【Python】考虑用生成器改写直接返回列表的函数

时间:2016-12-31 23:01:21      阅读:219      评论:0      收藏:0      [点我收藏+]

使用生成器的好处是显而易见的,可以使代码更加清晰,同时减小内存的消耗,当函数需要返回列表,把函数改写为生成器是相对容易的。

下面这两个函数返回字符串中每个单词的索引:

 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

【Python】考虑用生成器改写直接返回列表的函数

原文:http://www.cnblogs.com/fcyworld/p/6240389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!