
一个容器中存储了很多个东西,一般东西是按一定的规律规则来存储计算生成,但是容器中不可能什么东西都有的,人为的就会设一个限制,当超出这个限制范围,就会报异常。这时迭代器就会发挥作用。迭代器优点就是节省了空间,因为如果你想存储0~9这个字符串,你就需要劈开10个空间,但要是有了迭代器,那么你就开辟了一个空间。下面我们来看看迭代器的用法。
1、迭代文件
1 2 3 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); font-family: 微软雅黑,Microsoft YaHei; font-size: 14px;" > for line in open( 'ex.txt' ):
print (line, end = '' )<br></span></p>
|
输出:
1 2 3 4 5 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); font-family: 微软雅黑,Microsoft YaHei; font-size: 14px;" >I love Python
...
...<br></span></p>
|
2、迭代字符串
1 2 3 4 5 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); font-family: 微软雅黑,Microsoft YaHei; font-size: 14px;" >S = 'PYTHON'
for s in S:
print (s * 3)<br></span></p>
|
输出:
1 2 3 4 5 6 7 8 9 10 11 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); font-family: 微软雅黑,Microsoft YaHei; font-size: 14px;" >PPP
YYY
TTT
HHH
OOO
NNN<br></span></p>
|
3、迭代元组
1 2 3 4 5 6 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); font-family: 微软雅黑,Microsoft YaHei; font-size: 14px;" >L = (1,2,3,4,5)
for element in L:
print (str(element) * 3)
# 利用enumerate获取索引进行迭代
for i in enumerate(L):
print (i)<br></span></p>
|
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); font-family: 微软雅黑,Microsoft YaHei; font-size: 14px;" >111
222
333
444
555
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)</span><br></p>
|
以上就是小编向大家介绍用迭代器迭代文件、字符串、元组的方法,大家对迭代器有所了解了吗?迭代器这个抽象的东西,大家可以按照自己的需求来定义合适的迭代器哦~