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


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

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

     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

  • 相关阅读:
    Kafka速览
    分布式消息中间件(二)ActiveMQ
    PageUtil 分页
    Tomcat配置
    CryptographyUtil盐加密
    InitComponent的使用
    Shiro权限总结
    【转】Java自学之路——by马士兵
    ExcelUtil
    Java操作Excel之Poi
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6240389.html
Copyright © 2020-2023  润新知