# python迭代器和生成器

+关注继续查看

### 列表推导：

>>> [i for i in range(10) if i % 2 == 0]
[0,2,4,6,8]

### enumerate

seq = ["one","two","three"]
for i,element in enumerate(seq):
seq[i] = '%d:%s' % (i,seq[i])

### 迭代器：

>>> i = iter('abc')
>>> i.next()
'a'
>>> i.next()
'b'
>>> i.next()
'c'
>>> i.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> 

### 生成器

>>> def fibonacci():
...     a, b = 0, 1
...     while True:
...         yield b
...         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]
>>>

### 协同程序

#!/usr/bin/env python
#coding=utf-8
#协同
import time

def conroutine_1():
for i in range(3):
print 'c1'
yield i

def conroutine_2():
for i in range(3):
print 'c2'
yield i

def conroutine_3():
for i in range(3):
print 'c3'

def conroutine_4():
for i in range(3):
print 'c4'

print "==========协同========"

print "==========多线程========"
a.start()
b.start()

==========协同========
c1
c2
c1
c2
c1
c2
==========多线程========
c3
c3c4

c3
c4
c4

#!/usr/bin/env python
#coding=utf-8
from __future__ import with_statement
from contextlib import closing
import socket
def client_handler(sock):
with closing(socket):
while True:
if not data:
break

def echo_server(hostname,port):
socket.AF_UNSPEC,
socket.SOCK_STREAM)
with closing(socket.socket(family,socktype,proto)) as sock:
sock.listen(5)
while True:

if __name__=='__main__':
hostname = 'localhost'
port = 1111
try:
except KeyboardInterrupt:
pass

telnet localhost 1111

### itertools模块

##### islice：窗口迭代器
#!/usr/bin/env python
#coding=utf-8
import itertools
def starting_at_five():
value = raw_input("input1").strip()
while value != '':
for el in itertools.islice(value.split(),4,None):
yield el
value = raw_input("input2").strip()

iter = starting_at_five()
while True:
print iter.next()

input1: 1 2 3 4 5 6
5
6
input2: 1 2
input2: 1 2 3 4 5 6 7 8
5
6
7
8
input2: 

##### tee
#!/usr/bin/env python
#coding=utf-8
import itertools
a, b = itertools.tee(iterable)
seq = [1]
seq = [1,2,3,4]
with_head(seq,4)



[1] <itertools.tee object at 0xb71f866c>
[1, 2, 3, 4] <itertools.tee object at 0xb71f862c>

##### uniq迭代器：

#!/usr/bin/env python
#coding=utf-8
import itertools
def compress(data):
return ((len(list(group)),name)
for name,group in itertools.groupby(data))

def decompress(data):
return (car * size for size,car in data)

print list(compress('aaasdffffffffffffffffffffff'))
compressed = list(compress('aaasdffffffffffffffffffffff'))
print "".join(decompress(compressed))

[(3, 'a'), (1, 's'), (1, 'd'), (22, 'f')]
aaasdffffffffffffffffffffff

736 0
Python——列表生成式

672 0

7748 0
14、C++ Primer 4th 笔记，迭代器
1、三种迭代器 1）插入迭代器(insert iterator)：迭代器适配器，与容器绑定在一起，实现在容器中插入元素的功能。形参为一个迭代器和一个指向容器的引用。 • back_inserter，创建使用 push_back 实现插入的迭代器，形参为指向容器的引用的迭代器适配器。
827 0
javascript中的迭代器
1.forEach迭代器 forEach方法接收一个函数作为参数，对数组中每个元素使用这个函数，只调用这个函数，数组本身没有任何变化 //forEach迭代器 function square(num){ document.
704 0
+关注
4533

0

《SaaS模式云原生数据仓库应用场景实践》

《看见新力量：二》电子书