{{ message }}

lzjun567 / note Public

Switch branches/tags
Could not load branches
Nothing to show

Cannot retrieve contributors at this time
154 lines (101 sloc) 3.95 KB

迭代器(Iterator)与生成器(Generator)的区别

``````def squares(start, stop):
for i in xrange(start, stop):
yield i*i
``````

``````（i*i for i in xrange(start, stop))
``````

``````[i*i for i in xrange(start, stop)]
``````

``````class Squares(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self):
return self
def next(self):
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
``````

``````def current(self):
return self.start
``````

Iterables, Iterators, Genrators

热身一下

``````my_list = [17  23  47  51  101  173  999  1001]

i = 0
while i < len(my_list):
v = my_list[i]
print v,
i += 1
``````

``````17 23 47 51 101 173 999 1001
``````

``````for i in range(len(my_list)):
v = my_list[i]
print v,
``````

``````17 23 47 51 101 173 999 1001
``````

``````for v in my_list:
print v,
``````

``````17 23 47 51 101 173 999 1001
``````

``````for v in "Hello":
print v,
``````

``````H e l l o
``````

``````d = {
'a': 1,
'b': 2,
'c': 3,
}

for v in d:
print v,
# 注意这里是无序的
``````

``````a c b
``````

``````f = open("suzuki.txt")
for line in f:
print ">", line
``````

``````> On education

> "Education has failed in a very serious way to convey the most important lesson science can teach: skepticism."

> "An educational system isn't worth a great deal if it teaches young people how to make a living but doesn't teach them how to make a life."
``````

list构造器接收任何类型的Iteratbles，可以使用list()接收字典对象返回只有key的列表：

``````list(d)
``````

``````['a', 'c', 'b']
``````

``````list("Hello")
``````

``````['H', 'e', 'l', 'l', 'o']
``````

``````ascii = [ord(x) for x in "Hello"]
ascii
``````

``````[72, 101, 108, 108, 111]
``````

sum()函数接收任何数字类型的可迭代对象:

``````sum(ascii)
``````

``````500
``````

str.join()方法接收任何字符类型的可迭代对象 （这里的说法不严谨，总之原则是迭代的元素必须是str类型的)：

``````"-".join(d)
``````

``````‘a-c-b'
``````