http://blog.chinaunix.net/uid-26722078-id-3484197.html
1.列表推导
看几个例子,一切就明白了。
1 #!/usr/bin/python 2 numbers = range(10) 3 size = len(numbers) 4 evens = [] 5 i = 0 6 while i < size: 7 if i%2 == 0: 8 evens.append(i) 9 i += 1 10 print evens 11 12 #!/usr/bin/python 13 evens = [i for i in range(10) if i % 2 == 0] 14 print evens 15 16 #!/usr/bin/python 17 def _process(pos, element): 18 return '%d:%s' % (pos, element) 19 20 seq = ['a', 'b', 'c'] 21 print [_process(i, el) for i, el in enumerate(seq)]
备注:注意 enumerate用法
2.迭代器
迭代器只不过是实现迭代器协议的容器对象,基于next和__iter__两个方法
1 #!/usr/bin/python 2 class TestIterator(object): 3 def __init__(self, step): 4 self.step = step 5 def next(self): 6 """Return the next element""" 7 if self.step == 0: 8 raise StopIteration 9 self.step -= 1 10 return self.step 11 def __iter__(self): 12 """Return the iterator itself.""" 13 return self 14 print [el for el in TestIterator(4)]
3.生成器
next()和send()的工作机制一样,不过使用send(),yield将变成能够返回传入的值,因而可以据此来改变行为。
看两个例子,一切就明白了。
1 #!/usr/bin/python 2 def power(values): 3 for value in values: 4 print "powing %s" % value 5 yield value 6 def add(values): 7 for value in values: 8 if value % 2 == 0: 9 yield value + 3 10 else: 11 yield value + 2 12 elements = [1, 4, 7, 9, 12, 19] 13 res = add(power(elements)) 14 res.next()
1 #!/usr/bin/python 2 def psychologist(): 3 print "Please tell me your problems" 4 while True: 5 answer = (yield) 6 if answer is not None: 7 if answer.endswith('?'): 8 print("Don't ask yourself too much questions!") 9 elif 'good' in answer: 10 print("That's good, Let's go on") 11 elif 'bad' in answer: 12 print("It's a pity") 13 free = psychologist()