zoukankan      html  css  js  c++  java
  • list comprehension & generator expression

    List comprehensions(列表推导式) are better when you want to iterate over something multiple times. However,

    it's also worth noting that you should use a list if you want to use any of the list methods. Basically, use a

    generator expression(生成器推导式/生成器表达式) if all you're doing is iterating once. If you want to store and

    use the generated results, then you're probably better off with a list comprehension.

    Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> g = (x * 2 for x in xrange(2, 27))
    >>> g
    <generator object <genexpr> at 0xb71aff04>
    >>> g.next()
    4
    >>> g.next()
    6
    >>> l = [x * 2 for x in xrange(2, 27)]
    >>> l
    [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52]
    >>> type(l)
    <type 'list'>
    >>> type(g)
    <type 'generator'>
    >>> l.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'list' object has no attribute 'next'
    >>> g[0]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'generator' object has no attribute '__getitem__'
    >>> 

    生成器推导式( ), 列表推导式[ ]

    Reference:

    Generator Expressions vs. List Comprehension: http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension

  • 相关阅读:
    UVa 1374
    天梯赛L3 004
    redis操作ZSet
    redis操作set集合
    mybatis使用注解开发
    SSM整合之mybatis的别名配置
    mybatis的5.1.10分页插件的使用
    lombok的使用
    JDBC的一个简单工具类
    mybatis的测试
  • 原文地址:https://www.cnblogs.com/lxw0109/p/list_comprehension_and_generator_expression.html
Copyright © 2011-2022 走看看