(九)迭代

2019-01-02  本文已影响0人  费云帆

1.几个名词

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
>>> 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
>>> 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.'
上一篇下一篇

猜你喜欢

热点阅读