Posted on 2012-04-19 02:09
Tommy Liang 阅读(308)
评论(0) 编辑 收藏 引用
Syntax best practice:
-
List Comprehensions
>>> [i for i in range(10) if 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