Benx Blog

十月 23, 2009

Diigo Diary 10/23/2009

Filed under: Diigo Diary — benxshen @ 8:30 上午
  • tags: Python, Sort, programming, howto

  • tags: no_tag

    • Generators are a special class of functions that simplify the task of writing
      iterators. Regular functions compute a value and return it, but generators
      return an iterator that returns a stream of values.
    • When you call a generator function, it doesn’t return a single value; instead it
      returns a generator object that supports the iterator protocol. On executing
      the yield expression, the generator outputs the value of i, similar to a
      return statement. The big difference between yield and a return
      statement is that on reaching a yield the generator’s state of execution is
      suspended and local variables are preserved. On the next call to the
      generator’s .__next__() method, the function will resume executing.
    • In Python 2.5 there’s a simple way to pass values into a generator.
      yield became an expression, returning a value that can be assigned to
      a variable or otherwise operated on:

      val = (yield i)

      I recommend that you always put parentheses around a yield expression
      when you’re doing something with the returned value, as in the above example.

    • Generators also become coroutines, a more generalized form of subroutines.
      Subroutines are entered at one point and exited at another point (the top of the
      function, and a return statement), but coroutines can be entered, exited,
      and resumed at many different points (the yield statements).
    • enumerate(iter) counts off the elements in the iterable, returning 2-tuples
      containing the count and each element.

      >>> for item in enumerate(['subject', 'verb', 'object']):
      ...     print(item)
      (0, 'subject')
      (1, 'verb')
      (2, 'object')
    • zip(iterA, iterB, ...) takes one element from each iterable and
      returns them in a tuple:

      zip(['a', 'b', 'c'], (1, 2, 3)) =>
        ('a', 1), ('b', 2), ('c', 3)

      It doesn’t construct an in-memory list and exhaust all the input iterators
      before returning; instead tuples are constructed and returned only if they’re
      requested. (The technical term for this behaviour is lazy evaluation.)

  • tags: eclipse, plugin

Posted from Diigo. The rest of my favorite links are here.

發表迴響 »


RSS feed for comments on this post. TrackBack URI


在下方填入你的資料或按右方圖示以社群網站登入: 標誌

您的留言將使用 帳號。 登出 /  變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )


您的留言將使用 Facebook 帳號。 登出 /  變更 )


連結到 %s


%d 位部落客按了讚: