tommy

It's hard to tell the world we live in is either a reality or a dream
posts - 52, comments - 17, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Python 读书笔记

Posted on 2012-04-19 02:09 Tommy Liang 阅读(295) 评论(0)  编辑 收藏 引用
Syntax best practice:
  • List Comprehensions
    >>> [i for i in range(10if i % 2 == 0]

    Enumeration:
    >>> def _treatment(pos, element):
     return '%d: %s' % (pos, element)

    >>> seq = ["one""two""three"]
    >>> [_treatment(i, el) for i, el in enumerate(seq)]
    ['0: one''1: two''2: three']

    Iterators and Generators
    >>> def fibonacci():
     a, b = 0, 1
     while True:
     yield b  # 这里返回 generator,一个特殊的iterator
     a, b = b, a + b

    >>> fib = fibonacci()
    >>> fib.next()
    1
    >>> fib.next()
    1
    >>> fib.next()
    2
    >>> [fib.next() for i in range(10)]
    [3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
    generators should be considered every time you deal with a
    function that returns a sequence or works in a loop;
    It is better to have a lot of simple iterable functions that work over
    sequences of values than a complex function that computes the result for
    one value at a time.
    >>> def my_generator():
     try:
     yield 'something'
     except ValueError:
     yield 'dealing with the exception'
     finally:
     print "ok let's clean"

    >>> gen = my_generator()
    >>> gen.next()
    'something'
    >>> gen.throw(ValueError('mean mean mean'))
    'dealing with the exception'
    >>> gen.close()
    ok let's clean
    >>> gen.next()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理