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