chomperwu
迭代器
1
2
3
4
|
name
=
iter
(
'inter'
)
for
i
in
name:
#循环打印出迭代器中的内容
print
(i)
print
(
type
(i))
|
<class 'str_iterator'>
i
<class 'str'>
n
<class 'str'>
t
<class 'str'>
e
<class 'str'>
r
<class 'str'>
应用在文件操作中
1
2
3
4
5
6
7
|
f
=
open
(
'E:\暂存\新建文本文档.txt'
,
'r'
)
print
(
type
(f))
for
l
in
f:
print
(l)
#一行一行的打印出文件内容
f.close()
|
生成器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
def
getNum(x):
y
=
0
while
y < x:
yield
y
#返回y
y
+
=
1
#执行的时候,函数执行到yield语句处就停止了,等待下一次迭代
g
=
getNum(
10
)
print
(
type
(g))
#<class 'generator'>
#print(g.__next__())
#print(g.__next__())
for
i
in
g:
print
(i)
|
本文转自 chomperwu 51CTO博客,原文链接:http://blog.51cto.com/chomper/1941473,如需转载请自行联系原作者