python基础:迭代器及其使用方法

314次阅读
没有评论

python基础:迭代器及其使用方法

一个容器中存储了很多个东西,一般东西是按一定的规律规则来存储计算生成,但是容器中不可能什么东西都有的,人为的就会设一个限制,当超出这个限制范围,就会报异常。这时迭代器就会发挥作用。迭代器优点就是节省了空间,因为如果你想存储0~9这个字符串,你就需要劈开10个空间,但要是有了迭代器,那么你就开辟了一个空间。下面我们来看看迭代器的用法。

1、迭代文件

<p style="line-height: normal"><span style="font-family: 微软雅黑,Microsoft YaHei;font-size: 14px">for line in open('ex.txt'):

    print(line, end='')<br /></span></p>

输出:

<p style="line-height: normal"><span style="font-family: 微软雅黑,Microsoft YaHei;font-size: 14px">I love Python

...

...<br /></span></p>

2、迭代字符串

<p style="line-height: normal"><span style="font-family: 微软雅黑,Microsoft YaHei;font-size: 14px">S = 'PYTHON'

for s in S:

    print(s * 3)<br /></span></p>

输出:

<p style="line-height: normal"><span style="font-family: 微软雅黑,Microsoft YaHei;font-size: 14px">PPP

YYY

TTT

HHH

OOO

NNN<br /></span></p>

3、迭代元组

<p style="line-height: normal"><span style="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>

输出:

<p style="line-height: normal"><span style="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>

以上就是小编向大家介绍用迭代器迭代文件、字符串、元组的方法,大家对迭代器有所了解了吗?迭代器这个抽象的东西,大家可以按照自己的需求来定义合适的迭代器哦~

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python基础教程2022-12-07发表,共计549字。
新手QQ群:570568346,欢迎进群讨论 Python51学习