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

  • 相关阅读:
    P2519 [HAOI2011]problem a
    P1084 疫情控制
    P1941 飞扬的小鸟
    NOIP填坑计划
    P2831 愤怒的小鸟
    AGC 16 D
    P3960 列队
    Python3爬虫相关软件,库的安装
    软件理论基础—— 第一章命题逻辑系统L
    软件理论基础——导论
  • 原文地址:https://www.cnblogs.com/lxw0109/p/list_comprehension_and_generator_expression.html
Copyright © 2011-2022 走看看