您的位置:首页 > 编程语言 > Python开发

【脚本语言系列】关于Python基础知识迭代器,你需要知道的事

2017-07-21 12:00 976 查看

如何使用迭代器(Iterator)

迭代

可迭代对象

迭代器

# -*- coding:utf-8 -*-
the_string = "AllenMoore"
next(the_string)


---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-12-ed837072a8a2> in <module>()
1
2 the_string = "AllenMoore"
----> 3 next(the_string)

TypeError: str object is not an iterator


# -*- coding:utf-8 -*-
the_string = "AllenMoore"
the_iter = iter(the_string)
next(the_iter)


'A'


生成器

# -*- coding:utf-8 -*-
def gen_function():
for i in range(3):
yield i

for item in gen_function():
print item

gen = gen_function()
print '\n'
print next(gen)
print '\n'
print next(gen)
print '\n'
print next(gen)
print '\n'
print next(gen)


0
1
2

0

1

2

---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-10-c9cd08f2ec3a> in <module>()
15 print next(gen)
16 print '\n'
---> 17 print next(gen)

StopIteration:


# -*- coding:utf-8 -*-
def gen_fibonacci(n):
a = b = 1
result = []
for i in range(n):
result.append(a)
a, b = b, a+b
return result

for x in gen_fibonacci(20):
print x


1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765


# -*- coding:utf-8 -*-
def gen_fibonacci(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a+b

for x in gen_fibonacci(20):
print x


1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765


什么是迭代器(Iterator)

迭代(Iteration):从某个对象取出一个元素的过程;使用循环来遍历某个对象;

迭代器(Iterator):定义有next或者\_\_next\_\_方法的对象;遍历一个容器的对象;

可迭代对象(Iterable):定义有\_\_iter\_\_或者下标索引的\_\_getitem\_\_方法的对象;

生成器(Generator):迭代器之一;只能对其迭代一次,运行时生成值;

何时使用迭代器(Iterator)

不想同一时间将所有计算的结果集分配到内存的时候
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐