迭代器是一组数据结构,迭代器有一个next()方法的对象,而不是通过索引来计数.通过next()将条目全部取出后,会引发一个StopIteration异常,这并不是表示错误发生,只是告诉外部调用者,迭代完成.
>>> myTuple = (123, "xyz", 45.67) >>> i = iter(myTuple) >>> i.__next__() 123 >>> i.__next__() 'xyz' >>> i.__next__() 45.67 >>> i.__next__() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> i.__next__() StopIteration所以,对于for循环:
for i in seq: do_something_to(i)实际上等价于:
fetch = iter(seq) while True: try: i = fetch.__next__() except StopIteration: break do_something_to(i)
字典的迭代器会遍历它的键(key):
>>> dict1 = {"x" : 1, "y" : 2} >>> for key in dict1: print("key:%s, value:%s" % (key, dict1[key])) key:y, value:2 key:x, value:1
文件对象生成的迭代器会自动调用readline()方法.这样,循环就可以访问文本文件的所有行:
>>> with open("test.txt") as fobj: for eachLine in fobj: print(eachLine) hello world i love this world and i love python too
列表解析的语法如下:
[expr for iter_var in iterable]这个语句的核心是for循环,它迭代iterable对象的所有条目.前边的expr应用于序列的每个成员,最后的结果是该表达式产生的列表:
>>> [x ** 2 for x in range(6)] [0, 1, 4, 9, 16, 25]而我们甚至可以加上if判断:
>>> [x ** 2 for x in range(6) if x > 3] [16, 25]而列表中还可以存在双层for循环:
>>> [(x + 1, y + 1) for x in range(3) for y in range(5)] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]等价于:
>>> num = [] >>> for x in range(3): for y in range(5): num.append((x + 1, y + 1)) >>> num [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]