(九)迭代

1.几个名词

  • 循环(loop),指的是在满足条件的情况下,重复执行同一段代码。比如,while语句。
  • 迭代(iterate),指的是按照某种顺序逐个访问列表中的每一项。比如,for语句。
  • 递归(recursion),指的是一个函数不断调用自身的行为。比如,以编程方式输出著名的斐波纳契数列。
  • 遍历(traversal),指的是按照一定的规则访问树形结构中的每个节点,而且每个节点都只访问一次。

2.迭代的基本操作,除了for,还可以使用iter()

>>> list1=['q','i','w','s','i','r']
# 使用iter()创建一个迭代器
>>> list2=iter(list1)
# 使用.__next__()一直迭代下去
>>> list2.__next__()
'q'
>>> list2.__next__()
'i'
>>> list2.__next__()
'w'
>>> list2.__next__()
's'
>>> list2.__next__()
'i'
>>> list2.__next__()
'r'
# 迭代到最后会报错...因为末尾了
# 使用for不会报错
>>> list2.__next__()
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    list2.__next__()
StopIteration
# 懒惰一点的办法
# 需要重新赋值,因为已经迭代到末尾了
# 这也是迭代器的特点,要小心指针的位置
>>> list3=iter(list1)
>>> while True:
    print(list3.__next__())
q
i
w
s
i
r
Traceback (most recent call last):
  File "<pyshell#13>", line 2, in <module>
    print(list3.__next__())
StopIteration
  • 文件的迭代:之前的操作,使用readline()或者for()去遍历,这里使用next(),for的本质就是next():
>>> file=open('test3.txt')
# 文件对象不需要创建iter(),直接可以用
>>> file.__next__()
'Learn python with qiwsir.\n'
>>> file.__next__()
'There is free python course.\n'
>>> file.__next__()
'http://qiwsir.github.io\n'
>>> file.__next__()
'Its language is Chinese.'
>>> file.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
  • 还可以使用list(),tuple(),''.join()获取文件元素
>>> file=open('test3.txt')
>>> list(file)
['Learn python with qiwsir.\n', 'There is free python course.\n', 'http://qiwsir
.github.io\n', 'Its language is Chinese.']
# 需要重新赋值
>>> tuple(file)
()
>>> file=open('test3.txt')
>>> tuple(file)
('Learn python with qiwsir.\n', 'There is free python course.\n', 'http://qiwsir
.github.io\n', 'Its language is Chinese.')
>>> file=open('test3.txt')
>>> '$$$'.join(file)
'Learn python with qiwsir.\n$$$There is free python course.\n$$$http://qiwsir.gi
thub.io\n$$$Its language is Chinese.'
>>>
# 亮瞎眼的操作
>>> file=open('test3.txt')
# a,b,c,d,e=file 会报错,file有四个元素,赋值5个报错
# 赋值的元素要刚好.
>>> a,b,c,d=file
>>> a
'Learn python with qiwsir.\n'
>>> b
'There is free python course.\n'
>>> c
'http://qiwsir.github.io\n'
>>> d
'Its language is Chinese.'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 定义 迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示.组合模式允许你将对象组合成树...
    Link913阅读 3,558评论 0 1
  • 迭代 循环(loop),指的是在满足条件的情况下,重复执行同一段代码。比如,while语句。迭代(iterate)...
    hiekay阅读 2,860评论 0 0
  • 沉默寡言的唇 吃饭喝水 微笑哭泣 说话太没意思 全心全意为心发声 不如自己关爱自己 遇到巧舌如簧 乖乖投降 自启 ...
    天赋还没用到阅读 3,579评论 2 6
  • 杨云乔阅读 1,618评论 0 0
  • 一辈子有多久,有人给它的界定是一百年,有人界定不清只说是很久,我的界定是我们的爱有多久,一辈子就有多久~也...
    IDu21阅读 2,967评论 0 0